Reputation: 2226
How to change key of array into first element array ? I preferred using array_map.
Now I have a common array. If I have an array like this :
[
0 => [
'barang_id' => '7389'
'spec' => 'KCH8AT-DM'
'heat_no' => '7B4784'
'coil_no' => '0210'
'size' => '17.9'
'weight' => '2014'
'container' => 'TCLU6265556'
]
1 => [
'barang_id' => '7390'
'spec' => 'KCH8AT-DM'
'heat_no' => '7B4784'
'coil_no' => '0050'
'size' => '17.9'
'weight' => '2006'
'container' => 'TCLU6265556'
]
]
I need like this. The value of first element array is going to be key of array.
[
7389 => [
'barang_id' => '7389'
'spec' => 'KCH8AT-DM'
'heat_no' => '7B4784'
'coil_no' => '0210'
'size' => '17.9'
'weight' => '2014'
'container' => 'TCLU6265556'
]
7390 => [
'barang_id' => '7390'
'spec' => 'KCH8AT-DM'
'heat_no' => '7B4784'
'coil_no' => '0050'
'size' => '17.9'
'weight' => '2006'
'container' => 'TCLU6265556'
]
]
Please advise
Upvotes: 0
Views: 79
Reputation: 2022
I thought with this solution using array_map
$a = [['id' => 1233, 'name' => 'test1'], ['id' => 1313, 'name' => 'test2'], ['id' => 13123, 'name' => 'test3']];
$result = [];
array_map(
function ($item, $key) use (&$result) {
$result[$item['id']] = $item;
return $item; // you can ignore this
}, $a, array_keys($a)
);
now result contains what you want, check this image:
Or you could use it like this (without the $result thing) but you should unset the old key, look at the image:
Upvotes: 2
Reputation: 317197
You cannot use array_map
, because array_map
will not pass the keys to the callback. But array_walk
would work:
$reindexed = [];
array_walk($data, function($v, $k) use (&$reindexed) {
$reindexed[$v['barang_id']] = $v;
});
This has no advantage over a plain old foreach
though.
Upvotes: 1
Reputation: 32354
if you have only 2 values you can create a new array:
$newarray[7389] = $oldarray[0];
$newarray[7390] = $oldarray[1];
or if you have multiple values you can do:
$newarray =[];
foreach($oldarray as $value) {
$newarray[$value['barang_id']] = $value
}
demo:https://ideone.com/mm2T7T
Upvotes: 1