相交键后的Php数组排序关键字

时间:2015-11-22 23:59:35

标签: php arrays sorting array-intersect

目前我有这个:

$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之类的操作,而无需对键进行硬编码。

2 个答案:

答案 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)