PHP Merge Multidimensional Array成为一体

时间:2015-10-20 05:20:25

标签: php arrays multidimensional-array

我有这个数组

<div class="container">
   <div class="row">
       <div class="col-md-8">
           <div class="slider"></div>
           <!--divided column into 6/6-->
           <div class="col-md-6">
               <img src="img/2.jpg" style="width: 150px;height: 150px;" class="img-thumbnail" />
               <img src="img/2.jpg" style="width: 150px;height: 150px;" class="img-thumbnail"/>
               <img src="img/2.jpg" style="width: 150px;height: 150px;" class="img-thumbnail"/>
           </div>
           <div class="col-md-6">
               <p>some content with image</p>
           </div>
       </div>
       <div class="col-md-4">
           some content plus image
       </div>
   </div>
</div>

我如何将它们组合成:

array:2 [
  0 => array:2 [
    "monday_open" => "10:00:00"
    "monday_close" => "20:00:00"
  ]
  1 => array:2 [
    "tuesday_open" => "00:00:00"
    "tuesday_close" => "00:00:00"
  ]
]

我尝试过使用array_walk_recrusive,但它没有使用键名返回我:

array:4 [
  "monday_open" => "10:00:00"
  "monday_close" => "20:00:00"
  "tuesday_open" => "00:00:00"
  "tuesday_close" => "00:00:00"
]

我也试过这个,但得到了与array_walk_recrusive相同的结果:

array_walk_recursive($array, function ($v) use (&$arrayFlat) {
            $arrayFlat[] = $v;
        });

结果:

 iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0)

还有其他方法来保持键值吗?

2 个答案:

答案 0 :(得分:1)

试试这个

$source_array    =   array(array("monday_open"=>"10:00:00", "monday_close" => "20:00:00"), array("tuesday_open" => "00:00:00", "tuesday_close" => "00:00:00"));
$my_array        =   array();
foreach($source_array as $source){
    foreach($source as $key=> $val){
        $my_array[$key] = $val;
    }
}
print_r($my_array);

答案 1 :(得分:1)

您可以将密钥参数添加到array_walk_recursive这样的

的闭包中
array_walk_recursive($array, function ($v, $k) use (&$arrayFlat) {
        $arrayFlat[$k] = $v;
    });