2017-10-17 86 views
0

如何將數組的鍵轉換爲第一個元素數組? 我首選使用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' 
] 
] 

請告知

回答

1

如果你只有兩個值,你可以創建一個新的數組:

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

,或者如果你有多個值,你可以這樣做:

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

} 

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

1

您不能使用array_map,因爲array_map不會將密鑰傳遞給回調。但array_walk將工作:

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

這已超過一個普通的老foreach雖然沒有什麼優勢。

+0

這會更簡單用普通的foreach? – marekful

+0

@marekful是的,在我看來'foreach'會更簡單。它對我更具可讀性,它不需要參考或回調。 – Gordon

1

我認爲這個解決方案使用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

或者你可以使用它像這樣(沒有$結果東西),但你應該取消舊的關鍵,看看圖像: enter image description here