[英]Unset variable specific key from multidimensional array
我有不同的多維數組,它們具有不同的鍵和值:
$array_1 = array('cars' => array('audi' => array('a3' => array('one', 'two', 'three'), 'a5' => array('five', 'six', 'seven')), 'mercedes' => array('type_1' => array('submodel' => array('whatever'))), 'other_cat' => array('different_things')));
那么我想取消設置特定的鍵,例如:
unset($array_1['cars']['audi']['a5']);
現在,我喜歡“拆分”,以獲取鍵變量。
$to_unset = ['cars']['audi']['a5'];
如何取消設置該特定(可變!)鍵?
亞倫
一個簡單的實用程序,可以避免意外刪除不存在的數組鍵:
function removeArrayKey($path, &$array ) {
$array_temp = &$array;
$previousItem = null;
$path_bits = explode( ".", $path );
foreach( $path_bits as &$path_bit ) {
if( !isset( $array_temp[ $path_bit ] ) ) {
die("Error" . $path_bit);
//throw new Exception( "Path does not exist in array" );
}
$previousItem = &$array_temp;
$array_temp = &$array_temp[ $path_bit ];
}
if( isset( $previousItem ) ) {
unset( $previousItem[ $path_bit ] );
}
return $array;
}
要使用該函數,只需使用removeArrayKey( "cars.mercedes.cars", $array_1 );
並使用分隔每個數組索引.
因此,正如我看到的問題一樣,您想將數組路徑保存到變量中。 您可以通過兩種不同的方法解決此問題:
如果我的數組結構看起來始終相同(例如[cars] [type] [model]),我將采用這種方式。 您可以保存要刪除的密鑰到變量中:
$cars = 'cars';
$type = 'audi';
$model = 'a5';
unset($array_1[$cars][$type][$model]);
這在for(each)循環中效果很好。
這種方法可以節省您的問題,但這不是最佳選擇。 您可以將要取消設置的所有鍵保存到數組中。 這種方法可能會導致許多錯誤,如果您可以采用這種方法,則應該重新考慮數組結構。
// arrays start at 0
$to_unset = [
0 => 'cars',
1 => 'audi',
2 => 'a5',
];
unset($array_1[$to_unset[0]][$to_unset[1]][$to_unset[2]]);
這里的另一個可能的選擇是命名$ to_unset數組的鍵。
// arrays start at 0
$to_unset = [
'cars' => 'cars',
'type' => 'audi',
'model' => 'a5',
];
unset($array_1[$to_unset['cars']][$to_unset['type']][$to_unset['model']]);
您可能可以使用eval,但不建議這樣做 。
eval('unset($array_1' . $to_unset . ');');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.