我有一个动态数组。我在这里显示了该数组的一个实例。虽然存在not fixed how many keys
Array
(
[lowest] => 1200
[highest] => 139900
[cat_0] => Womens Clothing
[cat_1] => Smart Phones
[cat_2] => Mens Clothing
[cat_3] => Electronics
[chil_cat_0] => 18
[chil_cat_1] => 12
[chil_cat_2] => 7
[chil_cat_3] => 11
[chil_cat_4] => 17
[keyword] =>
)
对于这个数组,我想创建子数组.like。
Array
(
[cat_0] => Womens Clothing
[cat_1] => Smart Phones
[cat_2] => Mens Clothing
[cat_3] => Electronics
)
注意:基于类似的键。我必须将我的主数组分解为子数组
但是,主阵列可以有任意数量的相似行。
请帮帮我。
答案 0 :(得分:1)
您可以使用array_filter()
仅保留与您想要的键匹配的值:
$out = array_filter($array, function($key){
// Keep only keys that begins by 'cat_'
return substr($key, 0, 4) == 'cat_' ;
// or
return preg_match('~^cat_[\d]+~',$key) ; // Use cat_ + number
}, ARRAY_FILTER_USE_KEY);
print_r($out);
输出:
Array
(
[cat_0] => Womens Clothing
[cat_1] => Smart Phones
[cat_2] => Mens Clothing
[cat_3] => Electronics
)