我如何将这些数组合并在一起?

时间:2015-04-22 21:10:20

标签: php

我在将这些数组合并在一起时遇到了很多麻烦,我尝试过array_merge和array_merge_recursive但它们并没有给我我想要的结果。如果有人能指出我正确的方向,这将是惊人的,我现在已经敲了几个小时对着桌子......

数组1:

array [
  0 => array [
    "start" => "04/26/2015 8:00 AM"
  ]
  1 => array [
    "start" => "04/26/2015 9:00 AM"
  ]
]

数组2:

array [
  0 => array [
    "end" => "04/26/2015 10:00 AM"
  ]
  1 => array [
    "end" => "04/26/2015 11:00 AM"
  ]
]

数组3:

array:2 [
  0 => "1"
  1 => "3"
]

我想要的结果,不要担心" 2015-04-26"这与这个问题无关:

array [
  "2015-04-26" => array [
    "cities" => array [
      1 => array [
        "start" => "04/26/2015 8:00 AM"
        "end" => "04/26/2015 10:00 AM"
      ]
      3 => array [
        "start" => "04/26/2015 9:00 AM"
        "end" => "04/26/2015 11:00 AM"
      ]
    ]
  ]
]

2 个答案:

答案 0 :(得分:0)

这只是一个简单的for循环,它从每个输入数组中获取值并将它们组合到输出数组中。

$result = array('2015-04-26' > array('cities' => array()));
foreach ($array1 as $id => $val1) {
    $start = $val1['start'];
    $end = $array2[$id]['end'];
    $key = $array3[$id];
    $result['2015-04-26']['cities'][$key] = array('start' => $start, 'end' => $end);
}

答案 1 :(得分:0)

在这种特殊情况下,以下代码可以解决问题。但是你应该重新考虑你的数据结构。

$arrStart = [
    0 => [
        "start" => "04/26/2015 8:00 AM",
    ],
    1 => [
        "start" => "04/26/2015 9:00 AM",
    ],
];

$arrEnd = [
    0 => [
        "end" => "04/26/2015 10:00 AM",
    ],
    1 => [
        "end" => "04/26/2015 11:00 AM",
    ],
];

$keys = [
  0 => "1",
  1 => "3",
];

$result = [];

foreach ($keys as $i => $key) {
    $result[$key] = [
        'start' => $arrStart[$i]['start'],
        'end'   => $arrEnd[$i]['end'],
    ];    
}

var_dump($result);