Home > Software design >  Merge multidimensional Array PHP without changing the key
Merge multidimensional Array PHP without changing the key

Time:09-28

i have a problem to merge this array, I want to merge this array bellow

    Array
    (
       [0] => Array
           (
               [image] => logo.jpg
               [name] => data
               [server] => Mirani Rahmawati
               [6] => 5
           )

       [1] => Array
           (
               [image] => logo.jpg
               [name] => data
               [server] => Mirani Rahmawati
               [5] => 150
           )
       )
   

and the expected result will be like this

Array
(
    [0] => Array
        (
            [image] => logo.jpg
            [name] => data
            [server] => Mirani Rahmawati
            [6] => 5
            [5] => 150
        )

)

without changing the key..

Thankyou.

CodePudding user response:

You can use Array Operators to do that. You can check my below demo:

<?php

$array = [
  array(
    "image" => "logo.jpg",
    "name" => "data",
    "server"=> "Mirani Rahmawati",
     "6" => "5"
  ),
  array(
    "image"=> "logo.jpg",
    "name" => "data",
    "server"=> "Mirani Rahmawati",
     "5" => "150"
  )
];

$result = [];
foreach ($array as $item) {
   $result = $result   $item;
}

print_r($result);
exit;

?>

The result will be:

Array
(
    [image] => logo.jpg
    [name] => data
    [server] => Mirani Rahmawati
    [6] => 5
    [5] => 150
)

You can find out more at https://www.php.net/manual/en/language.operators.array.php

CodePudding user response:

<?php
$array = array();
$array[]  = array(
    "image" => "logo.jpg",
    "name" => "data",
    "server" => "Mirani Rahmawati",
    6 => 5
);
$array[]  = array(
    "image" => "logo.jpg",
    "name" => "data",
    "server" => "Mirani Rahmawati",
    5 => 150    
);

$new_array = array($array[0]   $array[1]);
var_dump($new_array);

Array Merge - Contribute Notes

  • Related