PHP合并/组合多维数组

时间:2014-06-06 09:39:34

标签: php arrays multidimensional-array

我有多维数组,

Array
(
    [address] => Array
        (
            [1] => skdbabsdkbakbskjabsd 
            [2] => skbdskbdkjbskjdbkjsb ksbdk bsdkb
        )

    [contact] => Array
        (
            [1] => 1236547890
            [2] => 654654654646464
        )

)

如何转换/合并成这样的东西,

Array
(
    [0] => Array
        (
            [1] => skdbabsdkbakbskjabsd 
            [2] => 1236547890
        )

    [1] => Array
        (
            [1] => skbdskbdkjbskjdbkjsb ksbdk bsdkb
            [2] => 654654654646464
        )

)

如下所述,我试图将第一个地址1和联系人1组合,同样地将地址2与联系人2结合起来等等。

解决此问题的任何解决方案?

3 个答案:

答案 0 :(得分:0)

如果您可以依赖数字键,我会这样做:

$result = array();
foreach ($address as $key => $value) {
    $result[] = array($address[$key], $contact[$key]);
}

答案 1 :(得分:0)

Here is link for the code

$address= Array
(
    "address" => Array
        (
            "skdbabsdkbakbskjabsd",
            "skbdskbdkjbskjdbkjsb ksbdk bsdkb"
        ),

    "contact" => Array
        (
            1236547890,
            6546546
        )

);


$result= array();
$i = 0;
foreach($address['address'] as $key => $value){
    $result[$i][] = $value;
    $result[$i][] = $address['contact'][$key];
    $i++;
}
echo '<pre>';
  print_r($result);
echo '</pre>';

答案 2 :(得分:0)

$data = array('adress' => array('1' => 'skdbabsdkbakbskjabsd', 
                                '2' => 'skbdskbdkjbskjdbkjsb ksbdk bsdkb'),
              'contact' => array('1' => '1236547890', 
                                 '2' => '654654654646464'));
echo '<pre>';    

print_r($data);

$mergedArray = array();
foreach($data['adress'] as $key => $adress){
    $mergedArray[] = array(1 => $adress, 2 => $data['contact'][$key]);
}


print_r($mergedArray);

echo '</pre>';

Array
(
    [adress] => Array
        (
            [1] => skdbabsdkbakbskjabsd
            [2] => skbdskbdkjbskjdbkjsb ksbdk bsdkb
        )

    [contact] => Array
        (
            [1] => 1236547890
            [2] => 654654654646464
        )

)
Array
(
    [0] => Array
        (
            [1] => skdbabsdkbakbskjabsd
            [2] => 1236547890
        )

    [1] => Array
        (
            [1] => skbdskbdkjbskjdbkjsb ksbdk bsdkb
            [2] => 654654654646464
        )

)