There is an array, how to make so that the array key is the same as the 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
)
)
I tried to do so, but it turns out the other way around, id becomes the same as the array key. It should be the other way around.
foreach ($statement as $key => $value) {
$statement[$key]['id'] = $key;
}
The part where you were mistaken is the usage of $key. Please see that $key refers to the keys of the main array i.e 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.
Code:
$newArray = array();
foreach ($statement as $value) {
$newArray[$value['id']] = $value;
}
Output:
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
)
)
foreach($array as $key => $val){
$new_array[$val['id']] = $val;
}
$array = $new_array;