1

我在php中得到以下数组,

[
 {
   Name0: "TEST",
   Value0: "13",
   Timestamp0: "2012-01-02 00:00:13"
 },
{
   Name0: "TEST",
   Value0: "16",
   Timestamp0: "2012-01-02 00:10:45"
 }
],
[
 {
   Name1: "TEST",
   Value1: "30",
   Timestamp1: "2012-01-02 00:00:13"
 },
{
   Name1: "TEST",
   Value1: "60",
   Timestamp1: "2012-01-02 00:10:45"
 }
]

更进一步,我希望它如下

[
 {
   Name0: "TEST",
   Value0: "13",
   Timestamp0: "2012-01-02 00:00:13",
   Name1: "TEST",
   Value1: "30",
   Timestamp1: "2012-01-02 00:00:13"
 },
{
   Name0: "TEST",
   Value0: "16",
   Timestamp0: "2012-01-02 00:10:45",
   Name1: "TEST",
   Value1: "60",
   Timestamp1: "2012-01-02 00:10:45"
 }
]

这真的让我的大脑array_merge和其他一些事情崩溃了 ;-) 希望有人能在这里帮助我吗?

4

3 回答 3

1

您可以简单地循环遍历它,长度为$array[0]

<?php
    for ($i = 0; $i < count($array[0]); $i++) {
        $array[0][$i] = array_merge($array[0][$i], $array[1][$i]);
    }
    $array = $array[0];
?>
于 2013-11-13T12:21:15.920 回答
0

试试这个:

<?php

    $arr1 = array(array('name0' => 'foo', 'val0' => '10'), 
            array('name0' => 'cde', 'val0' => '11'));
    $arr2 = array(array('name1' => 'bar', 'val1' => '20'), 
            array('name1' => 'fgh', 'val0' => '21'));

    $arr_mrg = array();

    for($i=0; $i<count($arr1); $i++){
         $arr_mrg[$i] = array_merge($arr1[$i], $arr2[$i]);
    }

    var_dump($arr_mrg); //test output of the result

?>
于 2013-11-13T14:10:28.340 回答
0

一种更通用的方式。

$loop_length = count($array[0]);
$new_array = array();
for($i=0; $i<$loop_length; $i++){
    for($j=0; $j<count($array); $j++){
        if(!array_key_exists($j,$new_array)) $new_array[$j] = array();
        $new_array[$j] = array_merge($new_array[$j],$array[$i][$j]);
    }
}

var_dump($new_array);
于 2013-11-14T03:54:04.450 回答