Viewed   67 times

How to merge n number of array in php. I mean how can I do the job like :
array_merge(from : $result[0], to : $result[count($result)-1])
OR
array_merge_recursive(from: $result[0], to : $result[count($result) -1])


Where $result is an array with multiple arrays inside it like this :

$result = Array(
0 => array(),//associative array
1 => array(),//associative array
2 => array(),//associative array
3 => array()//associative array
)

My Result is :

$result = Array(
    0 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 2
    ),
    1 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 3
    ),
    2 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 4
    ),
    3 => Array(
        "name" => "Name",
        "events" => 2,
        "types" => 2
    ),
    4 => Array(
        "name" => "Name",
        "events" => 3,
        "types" => 2
    )
)

And what I need is

$result = Array(
"name" => "name",
"events" => array(1,2,3),
"types" => array(2,3,4)
)

 Answers

3

array_merge can take variable number of arguments, so with a little call_user_func_array trickery you can pass your $result array to it:

$merged = call_user_func_array('array_merge', $result);

This basically run like if you would have typed:

$merged = array_merge($result[0], $result[1], .... $result[n]);

Update:

Now with 5.6, we have the ... operator to unpack arrays to arguments, so you can:

$merged = array_merge(...$result);

And have the same results. *

* The same results as long you have integer keys in the unpacked array, otherwise you'll get an E_RECOVERABLE_ERROR : type 4096 -- Cannot unpack array with string keys error.

Monday, October 17, 2022
1
$output = array();

$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
  $id = $value['id'];
  if ( !isset($output[$id]) ) {
    $output[$id] = array();
  }
  $output[$id] = array_merge($output[$id], $value);
}

var_dump($output);

Optionally if you want to reset output's keys, just do:

$output = array_values($output);
Tuesday, November 22, 2022
 
4

By assigning temporary keys, you can determine whether you are dealing with the first occurrence or not and then use the appropriate technique to either store the whole subarray or merely add value to the price element of the subarray.

Code: (Demo)

$to_account = [
  [ 'account' => 251234567890, 'price' => 83 ],
  [ 'account' => 251234567890, 'price' => 27 ],
  [ 'account' => 251234564526, 'price' => 180 ],
  [ 'account' => 251234567890, 'price' => 40 ]
];

foreach ($to_account as $row) {
    if (!isset($result[$row['account']])) {
        $result[$row['account']] = $row;
    } else {
        $result[$row['account']]['price'] += $row['price'];
        // imitate the above line if there was another column to sum
    }
}
var_export($result);

Output:

array (
  251234567890 => 
  array (
    'account' => 251234567890,
    'price' => 150,
  ),
  251234564526 => 
  array (
    'account' => 251234564526,
    'price' => 180,
  ),
)

This method does not bother to overwrite redundant account element values. To reindex the output array, merely call array_values() on it.

Sunday, October 16, 2022
2

This should do it, if I'm understanding your logic correctly:

array_intersect_key($changed, $filtered) + $filtered

Implementation:

$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
$expected = array(1 => 'a', 3 => 'c*');    
$actual = array_key_merge_deceze($filtered, $changed);

var_dump($expected, $actual);

function array_key_merge_deceze($filtered, $changed) {
    $merged = array_intersect_key($changed, $filtered) + $filtered;
    ksort($merged);
    return $merged;
}

Output:

Expected:
array(2) {
  [1]=>
  string(1) "a"
  [3]=>
  string(2) "c*"
}

Actual:
array(2) {
  [1]=>
  string(1) "a"
  [3]=>
  string(2) "c*"
}
Saturday, October 22, 2022
 
3

If both arrays are in the same order, the code is pretty straightforward:

$a = array(
    array('5/2/2013', '9:31:00 AM', '0.395', '0.395', '302.855', '0.563'),
    array('5/2/2013', '9:33:00 AM', '0.383', '0.383', '303.431', '0.563'),
);

$b = array(
    array('5/2/2013', '9:31:00 AM', '-1.000', '-1.000', '-1.000', '-1.670', '-1.000', '-11.000'),
    array('5/2/2013', '9:33:00 AM', '-1.000', '-1.000', '-1.000', '-1.670', '-1.000', '-11.000'),
);


$i = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
$i->attachIterator(new ArrayIterator($a), 'a');
$i->attachIterator(new ArrayIterator($b), 'b');

$result = [];
foreach ($i as $v) {
    $result[] = array_merge($v['a'], array_slice($v['b'], 2));
}
print_r($result);

You basically iterate over both arrays at the same time and for each element construct the final array by merging the first with the second (skipping the common part).

Result:

Array
(
    [0] => Array
        (
            [0] => 5/2/2013
            [1] => 9:31:00 AM
            [2] => 0.395
            [3] => 0.395
            [4] => 302.855
            [5] => 0.563
            [6] => -1.000
            [7] => -1.000
            [8] => -1.000
            [9] => -1.670
            [10] => -1.000
            [11] => -11.000
        )

    [1] => Array
        (
            [0] => 5/2/2013
            [1] => 9:33:00 AM
            [2] => 0.383
            [3] => 0.383
            [4] => 303.431
            [5] => 0.563
            [6] => -1.000
            [7] => -1.000
            [8] => -1.000
            [9] => -1.670
            [10] => -1.000
            [11] => -11.000
        )
)
Tuesday, August 16, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :