PHP foreach数组键

时间:2016-08-17 17:42:15

标签: php arrays foreach key

有一个数组,如何使数组键与id相同?

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Phones
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 2
            [title] => Apple
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 5
            [title] => Samsung
            [parent] => 1
        )
)

我试图这样做,但事实证明反过来,id变得与数组键相同。它应该是另一种方式。

foreach ($statement as $key => $value) {
    $statement[$key]['id'] = $key;
}

2 个答案:

答案 0 :(得分:0)

foreach($array as $key => $val){
 $new_array[$val['id']] = $val;
}

$array = $new_array;

答案 1 :(得分:0)

你弄错的部分是$ key的用法。请注意$ key是指主阵列的键,即0,1,2。

  

由于我们需要与密钥ID相对应的值, $ value ['id']   成为我们的结果数组$ newArray的关键。只需使用一个新变量   并将其存储在那里。

<强>代码:

$newArray = array();
foreach ($statement as $value) {
    $newArray[$value['id']] = $value;
}

<强>输出:

 Array
(
   [1] => Array
    (
        [id] => 1
        [title] => Phones
        [parent] => 0
    )
   [2] => Array
    (
        [id] => 2
        [title] => Apple
        [parent] => 1
    )

    [5] => Array
     (
        [id] => 5
        [title] => Samsung
        [parent] => 1
      )
)