0

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

3 Answers 3

2

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:

enter image description here

Or you could use it like this (without the $result thing) but you should unset the old key, look at the image: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

2 Comments

Would this be simpler with plain foreach?
@marekful yes, in my opinion a foreach would be simpler. it's more readable to me and it doesn't need a reference nor callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.