展平多维数组子项

时间:2015-09-08 09:06:46

标签: php multidimensional-array

我有一个PHP多维数组,如下所示。我想将另一个数组合并到这个数组中:

array(3) {
  [0]=>
  array(4) {
    ["id"]=> "1"
    ["register"]=> "Value 1"
    ["link"]=> "link 1"
    ["approval"]=> "yes"
  }
  [1]=>
  array(4) {
    ["id"]=> "2"
    ["register"]=> "Value 2"
    ["link"]=> "Value 2"
    ["approval"]=> "no"
  }
  [2]=>
  array(4) {
    ["id"]=> "3"
    ["register"]=> "Value 3"
    ["link"]=> "link 3"
    ["approval"]=> "pending"
  }
}

我想要合并的数组如下所示:

array(4) {
["image"]=> "123.png"
["start"]=> "8 October"
["end"]=> "9 October"
["days"]=> "2 Days"
}

每个第一个数组键都有一个如上所述的数组,需要合并到它中,这是唯一的。

我希望数组看起来如下:

array(3) {
  [0]=>
  array(8) {
    ["id"]=> "1"
    ["register"]=> "Value 1"
    ["link"]=> "link 1"
    ["approval"]=> "yes"
    ["image"]=> "image1.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
  [1]=>
  array(8) {
    ["id"]=> "2"
    ["register"]=> "Value 2"
    ["link"]=> "Value 2"
    ["approval"]=> "no"
    ["image"]=> "image2.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
  [2]=>
  array(8) {
    ["id"]=> "3"
    ["register"]=> "Value 3"
    ["link"]=> "link 3"
    ["approval"]=> "pending"
    ["image"]=> "image3.png"
    ["start"]=> "8 October"
    ["end"]=> "9 October"
    ["days"]=> "2 Days"
  }
}

我试过扁平化数组,但这会引起新的问题,因为我需要循环遍历每个数组,以后可以添加更多的值,这将使它非常大,所以我想保持每个部分在他们自己的数组中所以我可以在以后根据需要拆分它。

1 个答案:

答案 0 :(得分:1)

试试这个

$arr = array(0=>array(1=>"dsfdsf",2=>"udyauyd"),1=>array(1=>"dsfdsf",2=>"udyauyd"),2=>array(1=>"dsfdsf",2=>"udyauyd"));
$arr1 = array(3=>"asdasd",4=>"fdsjldksfj",5=>"yerteruywet");
foreach($arr as $value)
{
  $new_array[] = $value + $arr1;
}

print_r($new_array);

我使用了一些示例数组来演示逻辑。