Search code examples
phparraysmerging-data

Why isn't array_merge() merging arrays by reference?


echo $existing_data;

echo $current_data;

array_merge($existing_data->original, $current_data->original);
array_merge($existing_data->large, $current_data->large);
array_merge($existing_data->small, $current_data->small);

echo $existing_data;

The Output is:

"existing": {
    "original": [],
    "small": [],
    "large": [],
    "preview": {
      "name": "",
      "path": "",
      "reference": ""
    }
}

"current": {
    "original": [
      {
        "name": "TQT_82560100_1385618474_9480",
        "created_timestamp": "2013-11-28 06:01:14",
      }
    ],
    "small": [
      {
        "name": "TQT_82560100_1385618474_9480_small",
        "created_timestamp": "2013-11-28 06:01:15",
      }a
    ],
    "large": [
      {
        "name": "TQT_82560100_1385618474_9480_large",
        "created_timestamp": "2013-11-28 06:01:15",
      }
    ],
    "preview": {
      "name": "TQT_82560100_1385618474_9480_prev",
      "path": "images/",
      "reference": 0,
      "width": 137,
      "height": 137
    }
}

"existing": {
    "original": [],
    "small": [],
    "large": [],
    "preview": {
      "name": "",
      "path": "",
      "reference": ""
    }
}

I tried array_merge_recursive() too. But the same result.


Solution

  • you have to save the result of an array merge

    $result = array_merge($existing_data->original, $current_data->original);
    

    example of php docs

    <?php
       $array1 = array("color" => "red", 2, 4);
       $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
       $result = array_merge($array1, $array2);
       print_r($result);
    ?>
    

    Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )