在基于数组的第一个元素数组多维

时间:2017-10-17 04:51:32

标签: php arrays multidimensional-array

如何将数组的键更改为第一个元素数组? 我更喜欢使用array_map。

现在我有一个共同的数组。 如果我有这样的数组:

[
 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'
 ]
]

我需要这样的。第一个元素数组的值将成为数组的关键。

[
 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'
 ]
]

请告知

3 个答案:

答案 0 :(得分:2)

我想用这个解决方案使用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)
);

现在结果包含您想要的内容,请查看此图片:

enter image description here

或者你可以像这样使用它(没有$ result的东西)但是你应该取消设置旧密钥,看看图像: enter image description here

答案 1 :(得分:1)

如果您只有2个值,则可以创建新数组:

$newarray[7389] = $oldarray[0];
$newarray[7390] = $oldarray[1];

或者如果你有多个值,你可以这样做:

$newarray =[];
foreach($oldarray as $value) {
$newarray[$value['barang_id']] = $value

}

演示:https://ideone.com/mm2T7T

答案 2 :(得分:1)

您无法使用array_map,因为array_map不会将密钥传递给回调。但array_walk可行:

$reindexed = [];
array_walk($data, function($v, $k) use (&$reindexed) {
    $reindexed[$v['barang_id']] = $v;
});

这比普通的foreach没有优势。

相关问题