PHP foreach 数组键
PHP foreach array key
有个数组,如何让数组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;
}
foreach($array as $key => $val){
$new_array[$val['id']] = $val;
}
$array = $new_array;
你弄错的部分是$key的用法。请看 $key 是指主数组的键,即 0、1、2。
Since we need the value corresponding to key id, $value['id']
becomes the key of our result array $newArray. Just use a new variable
and store it in that.
代码:
$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
)
)
有个数组,如何让数组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;
}
foreach($array as $key => $val){
$new_array[$val['id']] = $val;
}
$array = $new_array;
你弄错的部分是$key的用法。请看 $key 是指主数组的键,即 0、1、2。
Since we need the value corresponding to key id, $value['id'] becomes the key of our result array $newArray. Just use a new variable and store it in that.
代码:
$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
)
)