我有两个数组secondArray
和mac_id
我必须将它们组合起来,以便根据$firstArray = [
[
'id' => 1,
'mac_id' => 2,
'type' => 'car'
],
[
'id' => 2,
'mac_id' => 2,
'type' => 'mobile'
],
[
'id' => 3,
'mac_id' => 1,
'type' => 'tv'
]
]
$secondArray = [
[
'id' => 1,
'mac_id' => 2,
'type' => 'fruit'
],
[
'id' => 2,
'mac_id' => 1,
'type' => 'car'
],
[
'id' => 3,
'mac_id' => 1,
'type' => 'car'
],
]
生成o / p
[
2 => [
'firstArray' => [
[
'id' => 1,
'mac_id' => 2,
'type' => 'car'
],
[
'id' => 2,
'mac_id' => 2,
'type' => 'mobile'
],
],
'secondArray' => [
[
'id' => 1,
'mac_id' => 2,
'type' => 'fruit'
]
]
],
1 => [
'firstArray' => [
[
'id' => 1,
'mac_id' => 2,
'type' => 'car'
],
[
'id' => 2,
'mac_id' => 1,
'type' => 'car'
]
],
'secondArray' => [
[
'id' => 3,
'mac_id' => 1,
'type' => 'car'
]
]
]
]
预期o / p
$(".mybox").select2({
containerCssClass: "pink",
templateResult: function (data, container) {
if (data.element) {
$(container).addClass($(data.element).attr("class"));
}
return data.text;
}
});
答案 0 :(得分:0)
从你的o / p希望这是你想要的
$firstArray = [
[
'id' => 1,
'mac_id' => 2,
'type' => 'car'
],
[
'id' => 2,
'mac_id' => 2,
'type' => 'mobile'
],
[
'id' => 3,
'mac_id' => 1,
'type' => 'tv'
]
];
$secondArray = [
[
'id' => 1,
'mac_id' => 2,
'type' => 'fruit'
],
[
'id' => 2,
'mac_id' => 1,
'type' => 'car'
],
[
'id' => 3,
'mac_id' => 1,
'type' => 'car'
],
];
if(count($secondArray) > count($firstArray))
$loop_through= $secondArray;
else
$loop_through= $firstArray;
$mac_id_array = array();
$new_array = array();
foreach ($loop_through as $key => $value) {
# code...
$mac_id =$value['mac_id'] ;
if(!in_array($mac_id, $mac_id_array))
{
$mac_id_array[]=$mac_id;
$key_1 = array_keys(array_column($firstArray, 'mac_id'),$mac_id);
$key_2 = array_keys(array_column($secondArray, 'mac_id'),$mac_id); //array_search($mac_id, array_column($secondArray, 'mac_id'));
if(count($key_1))
{
$tmp_array = array();
foreach ($key_1 as $tmp_key) {
$tmp_array[] = $firstArray[$tmp_key];
}
$new_array[$mac_id]['firstArray'] = $tmp_array;
}
if(count($key_2))
{
$tmp_array = array();
foreach ($key_2 as $tmp_key) {
$tmp_array[] = $secondArray[$tmp_key];
}
$new_array[$mac_id]['secondArray'] = $tmp_array;
}
}
}
echo "<pre>";
print_r($new_array);?>
检查o / p: