php合并数组问题

时间:2014-04-01 08:55:08

标签: php arrays merge

我有以下数组结构

array(
 0 => 'productItem' =>array(
         0=> object,
         1=> object 
      )

 1 =>'productItem' =>array(
         0=> object,
         1=> object 
      ) 

我得到的是

   $products = array();
             for($pages=1; $i <= 3; $pages++){                
              $res = $this->client->myfunc($pages,$other_params);
              $products[] = $res->productItems;
         }

我希望将所有ProductItem合并到一个数组

之下
0 => 'productItem' =>array(
             0=> object,
             1=> object, 
             2=> object,
             3=> object 
)

2 个答案:

答案 0 :(得分:0)

试试这个:

$arr = array(
    0 => array(
        'productItem' => array(new stdClass(), new stdClass())
    ),
    1 => array(
        'productItem' => array(new stdClass(), new stdClass())
    )
);

$newArr = array('productItem' => array());
foreach($arr as $subArr) {
    $newArr['productItem'] = array_merge($newArr['productItem'], $subArr['productItem']);
}
print_r($newArr);

输出:

Array
(
    [productItem] => Array
        (
            [0] => stdClass Object
                (
                )

            [1] => stdClass Object
                (
                )

            [2] => stdClass Object
                (
                )

            [3] => stdClass Object
                (
                )

        )

)

答案 1 :(得分:0)

组合数组中的所有数组:

$newArray = [];

foreach ($array as $item)
{
    $newArray = array_merge($newArray, $item['productItem']);
}

这将输出格式数组:

         0=> object,
         1=> object, 
         2=> object,
         3=> object