Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>array_merge_recursive</code> gets you very close (your "key" is in index 1 of leaf arrays, and your value is in index 0). So do it in two steps: first get the merged array, then fiddle with the branches to get it right.</p> <pre><code>// This is a callback for array_map() which should have some more generic uses. // array(array('k', 'v'), ...) -&gt; array('k' =&gt; 'v', ...) function flatten_branches($branches) { $newleaves = array(); foreach ($branches as $leaf) { $newleaves[$leaf[0]] = $leaf[1]; } return $newleaves; } function merge_flatten_branches($karray, $varray) { //$karray has the key-leaves, and $varray has the value-leaves $m1 = array_merge_recursive($karray, $varray); return array_map('flatten_branches', $m1); } $merged = merge_flatten_branches($array2, $array1); print_r($merged); </code></pre> <p>Just for fun, here are two more approaches. Both of these are a bit slower than <code>merge_flatten_branches</code>, but illustrate some useful array concepts. (In other more functional-flavored languages than php, these might be preferred.)</p> <pre><code>function merge_flatten_branches_reduce($karray, $varray) { //$karray has the key-leaves, and $varray has the value-leaves $m1 = array_merge_recursive($karray, $varray); return array_map('flatten_branches_reduce', $m1); } function merge_flatten_branches_add($karray, $varray) { //$karray has the key-leaves, and $varray has the value-leaves $m1 = array_merge_recursive($karray, $varray); return array_map('flatten_branches_add', $m1); } // The functions below are callbacks for the two above. function array_add($a1, $a2) { return $a1+$a2; } function flatten_leaf($leaf) { return array($leaf[0] =&gt; $leaf[1]); } function flatten_branches_add($branches) { $leaves = array_map('flatten_leaf', ($branches)); $finalleaves = array(); foreach ($leaves as $leaf) { $finalleaves += $leaf; } return $finalleaves; } function flatten_branches_reduce($branches) { $l = array_map('flatten_leaf', ($branches)); return array_reduce($l, 'array_add', array()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload