将新数组附加到现有数组

时间:2015-01-12 10:40:45

标签: php arrays codeigniter

我正在使用Codeigniter Sessions来构建一个" Betslip"。

我将球队名称和赔率添加到投注单,然后计划循环每个"下注"元素来创建一个betslip。

理想阵列需要看起来像:

 [betslip] => Array
        (
            [bet] => Array
                (
                    [team] => Rayo Vallecano
                    [odds] => 67/100
                )
            [bet] => Array
                (
                    [team] => Elche
                    [odds] => 1/100
                )
        )

但是在我的代码中,我似乎只是覆盖了已有的内容。

我目前的PHP代码如下:

// Get Team Name
    $teamname = $this->uri->segment(3);

    // Get Odds
    $odds1 = $this->uri->segment(4);
    $odds2 = $this->uri->segment(5);

    $odds = $odds1;
    $odds .= "/";
    $odds .= $odds2;

    // Build An array titled Bet
    $bet = array(
        'bet' => array(
            'team'  =>  urldecode($teamname),
            'odds'  =>  $odds
        )
    );

    $betslip = $this->session->userdata('betslip');

    // Create The Betslip For The First Time...
    if(empty($betslip))
    {
        $this->session->set_userdata('betslip', $bet);
    }
    else
    {
        // Add To The Betslip Array...
        $betslip['bet'] = array(
            'team'  =>  urldecode($teamname),
            'odds'  =>  $odds
        );

        $this->session->set_userdata('betslip', $betslip);
    }

我如何才能在现有投注单数据上下注?

是否可以使用多个具有相同名称的数组键?

提前致谢..

1 个答案:

答案 0 :(得分:1)

这不是理想数组

[betslip] => Array
        (
            [bet] => Array
                (
                    [team] => Rayo Vallecano
                    [odds] => 67/100
                )
            [bet] => Array
                (
                    [team] => Elche
                    [odds] => 1/100
                )
        )

它应该像

[betslip] => Array
        (
            [0] => Array
                (
                    [team] => Rayo Vallecano
                    [odds] => 67/100
                )
            [1] => Array
                (
                    [team] => Elche
                    [odds] => 1/100
                )
        )

<?php
$item = array();

$item2 = array(
    'team' => 1,
    'odds' => "1/100"
);



for ($x = 0; $x <= 10; $x++) {
    $item[] = $item2;
}

print_r($item);

?>