PHP: How do I combine multiple associative arrays into a multidimensional array?

。_饼干妹妹 提交于 2019-12-13 07:47:01

问题


Consider three associative arrays in php:

$a1 = array(
"a" => "1",
"b" => "2",
"c" => "3"
);

$a2 = array(
"d" => "4",
"e" => "5",
"f" => "6"
);

$a3 = array(
"g" => "7",
"h" => "8",
"i" => "9"
);

How would you efficiently combine these into a multidimensional array as follows:

$result = array(
"1" => array("4","7"),
"2" => array("5","8"),
"3" => array("6","9")
);

Thanks in advance!


回答1:


Very similar to a couple of questions I answered last night:

$a1 = array(
"a" => "1",
"b" => "2",
"c" => "3"
);

$a2 = array(
"d" => "4",
"e" => "5",
"f" => "6"
);

$a3 = array(
"g" => "7",
"h" => "8",
"i" => "9"
);

$x = array_combine(
    $a1,
    call_user_func_array('array_map', [null, $a2, $a3])
);
var_dump($x);



回答2:


Fairly straight forward:

foreach($a1 as $val) {
    $result[$val] = array(array_shift($a2), array_shift($a3));
}



回答3:


Is this what you mean?

  <?php

$a1 = array(
    "a" => "1",
    "b" => "2",
    "c" => "3"
);

$a2 = array(
    "d" => "4",
    "e" => "5",
    "f" => "6"
);

$a3 = array(
    "g" => "7",
    "h" => "8",
    "i" => "9"
);

$a1_ = array_values($a1);
$a2_ = array_values($a2);
$a3_ = array_values($a3);

$newarray = array();
$max = count($a1_);
for($i = 0; $i < $max; $i++) {
    $newarray[$a1_[$i]] = array($a2_[$i], $a3_[$i]);
}

var_dump($newarray);

which outputs

array(3) {
  [1]=>
  array(2) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "7"
  }
  [2]=>
  array(2) {
    [0]=>
    string(1) "5"
    [1]=>
    string(1) "8"
  }
  [3]=>
  array(2) {
    [0]=>
    string(1) "6"
    [1]=>
    string(1) "9"
  }
}



回答4:


First combine all of the arrays into a single multi-dimensional array.

$arrays = array();
array_push($arrays,$a1) //Do the same for the rest

Create another array and loop through the one we just created.

$result = array();
foreach($arrays as $a) {
    $result[$a[0]] = array_shift($a);
}

This pulls the first value out of the array and makes it the key. It then uses array_shift to pop out the first element of the array so it is not included in the assignment.

Is this along the lines of what you are looking for?

Note: This is scaleable for any size array and any number of arrays. Just add any array you want included into $arrays using array_push and it will follow the pattern you outlined above.



来源:https://stackoverflow.com/questions/30108691/php-how-do-i-combine-multiple-associative-arrays-into-a-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!