我有两个阵列。
第一个数组包含搜索关键字:
$search=Array ( [0] => iphone [1] => grey )
第二个数组包含一些键值,如下所示。
$required_data=Array (
'iphonewhite' => "val1",
'iphonesilver' => "val1",
'iphonegrey' => "val1",
'iphonegrey silver' => "val1",
'iphonesilverwhiterose' => "val1",
)
我需要根据第一个数组搜索关键字对第二个数组进行排序。即如果key具有第一个数组的所有关键字应该是第一个。
预期输出为:
$data=Array (
'iphonegrey' => "val1",
'iphonegrey silver' => "val1",
'iphonewhite' => "val1",
'iphonesilver' => "val1",
'iphonesilverwhiterose' => "val1",
)
我有以下想法来做这件事。
还有其他办法吗?
答案 0 :(得分:2)
试试这个:
$search=array ( 0 => 'iphone', 1 => 'grey' );
$required_data=array (
'iphonewhite' => "val1",
'iphonesilver' => "val1",
'iphonegrey' => "val1",
'iphonegrey silver' => "val1",
'iphonesilverwhiterose' => "val1",
);
$searchStr = implode('', $search); //get the search string
$matchArray = array();
$notMatchArray = array();
foreach($required_data as $key=>$val){
if(strpos($key, $searchStr) === false){ //find search string if it exist in array key or not
$notMatchArray[$key] = $val;
}else{
$matchArray[$key] = $val;
}
}
echo 'Final array';
print_r(array_merge($matchArray, $notMatchArray)); //merge two array