[英]How to unset numeric index elements from a PHP array?
我有一個數組的集合,它包含數字索引和非數字。 我想取消設置所有數字索引。
我的陣列是這樣的。
Array
(
[554] => Array
(
[0] => 554
[1] => Jiaqi Zheng
[2] => Female
[3] => 28
[4] => Table Tennis
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 554
[athlet_name] => Jiaqi Zheng
[gender] => Female
[sport] => Table Tennis
)
[555] => Array
(
[0] => 555
[1] => Zach Ziemek
[2] => Male
[3] => 23
[4] => Athletics
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 555
[athlet_name] => Zach Ziemek
[gender] => Male
[sport] => Athletics
)
)
在這里,我必須取消設置所有的數字索引。
我這樣使用unset,它對我來說很好。
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][0],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][1],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][2],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][3],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][4],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][5],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][6],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][7],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][8]
);
有什么辦法可以減少代碼行嗎? 這里0到8是一個系列。
我可以在一行代碼中取消設置所有索引,因為它們都是數字的嗎?
是否可以使用正則表達式?
我想要類似的東西
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][anything_which_will_take_index_from_0_to_8]);
有什么建議?
謝謝
您可以使用帶有is_string()
函數的array_filter()
作為其回調函數:
$array = array_filter($array, 'is_string', ARRAY_FILTER_USE_KEY);
使用循環。
foreach ($array as $key => $value) {
if (is_numeric ($key)) {
unset($array [$key]);
}
}
或者使用array_filter
$filtered = array_filter(
$array,
function ($key) {
return !is_numeric($key);
},
ARRAY_FILTER_USE_KEY
);
你應該使用帶有is_numeric
函數的foreach
循環
foreach ($your_array as $key => $value) {
if (!is_numeric($key)) {
unset($arr[$key]);
}
}
我認為不需要任何正則表達式
因為你必須array
內部array
第一你需要使用array_map()
然后通過使用陣列遍歷array_filter()
考慮$array
作為你的array
:
$resultData = array_map([$this, 'allData'], $array);
public function allData($data)
{
$numericKeys = array_filter(array_keys($data), function ($k) {
return is_int($k);
});
// Updated Code
$arrayKeys = array_diff(array_keys($data),$numericKeys);
return array_intersect_key($data,array_flip($arrayKeys));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.