目前我有这个:
$pattern = array('industry_id','category_id','subcategory_id');
$data = array('advert_id' => string '261501' (length=6)
'advert_type_id' => string '7' (length=1)
'user_id' => string '6221' (length=4)
'industry_id' => string '17' (length=2)
'category_id' => string '769' (length=3)
'subcategory_id' => string '868' (length=3)
'model' => string 'Custom Semi Drop Deck Trailer' (length=29)
'description' => string 'Industry: Trailer );
然后:
array_intersect_key( $data , array_flip($pattern) );
使用array_interect_key
& array_flip
根据$data
获取$pattern
的值,我会得到如下结果:
array (size=3)
'category_id' => string '769' (length=3)
'subcategory_id' => string '930' (length=3)
'industry_id' => string '17' (length=2)
不幸的是,您可以看到结果键排序与我在$pattern
中声明的不同。有没有像我在$pattern
中声明的那样对其进行排序的简写方法,因为在此之后我想要破坏数组并执行类似industry_id.category_id.subcategory_id
之类的操作,而无需对键进行硬编码。
答案 0 :(得分:3)
由于您已经找到了 array_intersect_key 方法,它无法获得$ pattern所需的键排序,请尝试以下方法:
// since original $pattern is not ASSOC (only vals)
// flip it so defined vals become keys
$pattern_flipped = array_flip($pattern);
$result = array();
foreach ($pattern_flipped as $k => $v) {
if (isset($data[$k])) {
$result[$k] = $data[$k];
}
}
var_dump($result); // test
// can use original 0 1 2 dynamic keys for concatenation
echo $result[$pattern[0]], $result[$pattern[1]], $result[$pattern[2]], '<br>';
// or use hardcoded keys
echo $result['industry_id'], $result['category_id'], $result['subcategory_id'], '<br>';
答案 1 :(得分:0)
您知道我不确定您是如何获得您描述的结果的。我已经尝试了你的代码,我得到了
array (size=3)
'industry_id' => string '17' (length=2)
'category_id' => string '769' (length=3)
'subcategory_id' => string '868' (length=3)
虽然使用array_filter
,但您可以采用另一种方式$newData = array_filter($data, function($key) use ($pattern) {
if (in_array($key, $pattern))
return true;
}, ARRAY_FILTER_USE_KEY)