如何从关联数组 PHP 中删除所有特定键



我必须从如下所示的关联数组中取消设置所有"优先级"键和值。尚找不到解决方案。

您认为从整个数组中删除特定键值对的最佳方法是什么?

$countries = array(
'AE' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
'priority' => 40,
),
'city' => array(
'priority' => 50,
),
),
'AF' => array(
'state' => array(
'priority' => 65,
),
),
'AO' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'label' => __( 'Province', 'woocommerce' ),
'priority' => 70,
),
),
// + another arrays
);

编辑

我找到的解决方案:

foreach( $countries as $country => $fields ) {
foreach( $fields as $field => $options ) {
if ( isset( $options['priority'] ) ) {
unset( $countries[$country][$field]['priority'] );
}
}
}

但我仍然想知道是否有其他更好的选择,编写的代码更少,可能是一些预定义的函数。

<?php
$countries = array(
'AE' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'priority' => 50,
),
),
'AF' => array(
'state' => array(
'priority' => 65,
),
),
'AO' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'label' => ['Province', 'woocommerce'],
'priority' => 70,
),
),
// + another arrays
);
foreach($countries as &$country) {
if(array_key_exists('state', $country)
&& array_key_exists('priority', $country['state'])) {
unset($country['state']['priority']);
}
}
var_dump($countries);
<?php
$countries = array(
'AE' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'priority' => 50,
),
),
'AF' => array(
'state' => array(
'priority' => 65,
),
),
'AO' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'label' => ['Province', 'woocommerce'],
'priority' => 70,
),
),
// + another arrays
);
function unset_recursive(&$array, $key) {
unset($array[$key]);
foreach ($array as &$value) {
if (is_array($value)) {
unset_recursive($value, $key);
}
}
}
unset_recursive($countries, 'priority');
var_dump($countries);

请尝试此操作,此代码可以搜索 2 的 deapth。

<?php
$countries = array(
'AE' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
'priority' => 50,
),
'state'    => array(
'priority' => 50,
),
),
'AF' => array(
'state' => array(
'priority' => 65,
),
),
'AO' => array(
'postcode' => array(
'required' => false,
'hidden'   => true,
),
'state'    => array(
'label' => ['Province', 'woocommerce'],
'priority' => 70,
),
),
// + another arrays
);
$lookKey = 'priority';
foreach($countries as $key => $country) {
if(array_key_exists($lookKey, $country)){
//echo "n $key - $lookKey";
unset($countries[$key][$lookKey]);
}else{
foreach($country as $subKey => $ar){    
if(array_key_exists($lookKey, $ar)){
//echo "n $key - $subKey - $lookKey";
unset($countries[$key][$subKey][$lookKey]);
}
}
}

}
print_r($countries);

希望这对你有帮助。

相关内容

  • 没有找到相关文章

最新更新