PHP从for循环构建一个关联数组

时间:2014-08-04 11:59:20

标签: php associative-array

我需要从for循环生成以下关联数组。

Array ( [0] => 
    Array ( 
            [id] => 1 
            [value] => 6

        ) [1] => 
        Array ( 
                [id] => 2 
                [value] => 7 

        ) [2] => 
        Array ( 
                [id] => 3 
                [value] => 8 

        ) 
    )

试过这段代码

 $total_pages = 3;
 $pagination = array();
 for ($i=1; $i<=$total_pages; $i++) {
                $pagination[]['id'] = $i;
                $pagination[]['value'] = $i + 5;
            };

我尝试过这段代码但无法生成关联数组。不确定如何做到这一点。请帮我解决这个问题。谢谢

3 个答案:

答案 0 :(得分:3)

如果你离开[],你就会在每次迭代时生成一个子数组,如果你提供索引而不是它会起作用:

$total_pages = 3;
$pagination = array();
for ($i=1; $i<=$total_pages; $i++) {
  $pagination[$i - 1]['id'] = $i;
  $pagination[$i - 1]['value'] = $i + 5;
};

答案 1 :(得分:3)

我认为这是最简单的选择:

$total_pages = 3;
$pagination = array();
for ($i=1; $i<=$total_pages; $i++) {
  $pagination[] = array('id' => $i, 'value' => $i+5);
};

...如果我检查其他答案,也是最短的。

答案 2 :(得分:2)

试试这个

$total_pages = 3;
 $pagination = array();
 for ($i=1; $i<=$total_pages; $i++) {
    $arr_temp = array();
    $arr_temp['id'] = $i;
    $arr_temp['value'] = $i + 5;
    $pagination[] = $arr_temp;
};
print_r($pagination);

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 6
        )

    [1] => Array
        (
            [id] => 2
            [value] => 7
        )

    [2] => Array
        (
            [id] => 3
            [value] => 8
        )

)

<强> Wording Demo