0

我试图想出一种方法,将两个具有不同键名和相同值的数组结合起来?匹配值的顺序可能不同,因此需要检查它是否匹配,如果是则合并。有没有简单的方法可以完成?任何帮助或指导表示赞赏。

阵列 1

Array
(
[0] => Array
    (
        [location_id] => 1
        [location_title] => Centralia
        [location_slug] => Centralia
        [state_name] => Illinois
    )

[1] => Array
    (
        [location_id] => 3
        [location_title] => Columbia
        [location_slug] => columbia
        [state_name] => Illinois
    )

[2] => Array
    (
        [location_id] => 15
        [location_title] => Dixon Hennepin
        [location_slug] => dixon-hennepin
        [state_name] => Illinois
    )
)

阵列 2

Array
(
[0] => Array
    (
        [hours_locationid] => 3
    )

[1] => Array
    (
        [hours_locationid] => 1
    )

[2] => Array
    (
        [hours_locationid] => 15
    )
)

结果

Array
(
[0] => Array
    (
        [location_id] => 1
        [location_title] => Centralia
        [location_slug] => Centralia
        [state_name] => Illinois
        [hours_locationid] => 1
    )

[1] => Array
    (
        [location_id] => 3
        [location_title] => Columbia
        [location_slug] => columbia
        [state_name] => Illinois
        [hours_locationid] => 3
    )

[2] => Array
    (
        [location_id] => 15
        [location_title] => Dixon Hennepin
        [location_slug] => dixon-hennepin
        [state_name] => Illinois
        [hours_locationid] => 15
    )
)
4

3 回答 3

0
foreach($array1 as $i => $data) {
  if(array_search(array('hours_locationid'=>$data['location_id']), $array2) !=== false)
     $array1[$i]['hours_locationid'] = $data['location_id'];
}
于 2012-06-25T17:18:00.670 回答
0
foreach ($array1 as $val1) {

    foreach ($array2 as $key => $val2) {

        if ($val1['location_id'] == $val2['hours_locationid']) {

            $val1['hours_locationid'] = $val2['hours_locationid'];
            $results[] = $val1;
            unset($array2[$key]);
        }
    }
}

var_dump($results);

应该可以工作,尽管正如评论中提到的那样,这是非常微不足道的

于 2012-06-25T17:24:47.413 回答
0

试试下面这个,

替换 $array1 和 $array2 -> 演示:http ://codepad.org/1inDuoVe

<?php
$array1 = array(array("a"=>"aaa","b"=>"bbb"),array("x"=>"xxx","y"=>"yyy"));
$array2= array(array("c"=>"ccc"),array("z"=>"zzz"));
$i=0;
$j=0;
foreach($array2 as $single){
    foreach($array1 as $multiple){
        if($i == $j){
            $keys = array_keys($single);

            print $key = $keys[0];
            $multiple = array_push_assoc($multiple,$key,$single[$key]);
            $array1[$j] = $multiple;
        }
        ++$j;
    }
    ++$i;
}

var_dump($array1);

function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
?>
于 2012-06-25T17:49:26.977 回答