我想用一个特定的键将一个数组的值移动到另一个数组,例如下面是我的第一个数组.
firstArray
(
[0] => Array
(
[id] => 863
[flag] => 2
[qty] => 2
[size] => 8
)
[1] => Array
(
[id] => 861
[flag] => 2
[qty] => 2
[size] => 8
)
)
以下是我的第二个阵列
TwoArray
(
[863] => Bead Headed Prince Nymphs size 18
[861] => Bead Headed Prince Nymphs size 14
)
我想要像组合值一样的数组
mainarray(
[0] => Array
(
[id] => 863
[flag] => 2
[qty] => 2
[size] => 8
[name] =>Bead Headed Prince Nymphs size 18
)
[1] => Array
(
[id] => 861
[flag] => 2
[qty] => 2
[size] => 8
[name] => Bead Headed Prince Nymphs size 14
)
)
$getResult = $wpdb->get_results("SELECT *FROM tablename");
if(isset($getResult) && !empty($getResult)){
foreach($getResult as $val){
$data = $val->fliesfromuser;
$fliesFromStore = json_decode($val->fliesid_in_store,true);
@$result = call_user_func_array('array_merge', $fliesFromStore);
echo "<pre>first";
print_r ($fliesFromStore);
echo "</pre>";
$postIds = array_column($fliesFromStore, 'id');
$args = array(
'post__in' =>$postIds,
'post_type' =>'product'
);
$getStorePosts = get_posts($args);
$postTitle = array_column($getStorePosts, 'post_title','ID');
echo "<pre>Two";
print_r ($postTitle);
echo "</pre>";
$test = array_merge($fliesFromStore,$postTitle);
echo "<pre>";
print_r ($test);
echo "</pre>";
die();
}
}
如果有人在我的代码中知道我做错了什么,那么请帮助我.
解决方法:
如果你将第一个数组关联起来,那么它就是一个简单的foreach循环.
您可以使用array_column使firstarray关联.
// Make firstarray associative
$firstarray = array_column($firstarray, NULL,"id");
foreach($twoarray as $key => $val){
$firstarray[$key]['name'] = $val;
}
var_dump($firstarray);
请注意,firstarray是关联的,要删除关联,如果需要,可以使用array_values.
编辑:请记住,此代码假定第二个数组中的键存在于第一个中.
如果它不存在,它将在第一个数组中创建一个只有’name’的新项.
您可以使用isset()首先确保$key存在于firstarray中.
foreach($twoarray as $key => $val){
if(isset($firstarray[$key])) $firstarray[$key]['name'] = $val;
}