0

Now I have an array looks like this

Array([0] => array([region]=>1[district]=>2[sell]=>3)
      [1] => array([region]=>1[district]=>3[sell]=>6)
      [2] => array([region]=>1[district]=>4[sell]=>9)
     )

And I have an other array look like this

Array([0] => array([buy]=>3)
      [1] => array([buy]=>4)
      [2] => array([buy]=>5)
     )

So the question is how can i combine two array to make it looks like this ? or is there any method to push the second array into the first array?

Array([0] => array([region]=>1[district]=>2[sell]=>3[buy]=>3)
      [1] => array([region]=>1[district]=>3[sell]=>6[buy]=>4)
      [2] => array([region]=>1[district]=>3[sell]=>9[buy]=>5)
     )
user3571945
  • 184
  • 1
  • 14

2 Answers2

1

Do not forget about functional programming.

$existing = [
    ['a' => 1, 'b' => 2, 'c' => 3],
    ['a' => 4, 'b' => 5, 'c' => 6],
    ['a' => 5, 'b' => 8, 'c' => 9],
];
$newItems = [
    ['d' => 3],
    ['d' => 4],
    ['d' => 5]
];
// let's run over those arrays and do array_merge over items
$result = array_map('array_merge', $existing, $newItems);
var_dump($result);

P.S. There is exist more simple way using array_replace_recursive

$result2 = array_replace_recursive($existing, $newItems);
sectus
  • 15,605
  • 5
  • 55
  • 97
0

Try this

$existing = array(
    0 => array('region'=>1, 'district'=>2, 'sell'=>3),
    1 => array('region'=>4, 'district'=>5, 'sell'=>6),
    2 => array('region'=>5, 'district'=>8, 'sell'=>9),
);

$newItems = array(
    0 => array('buy'=>3),
    1 => array('buy'=>4),
    2 => array('buy'=>5)
);

foreach($newItems as $i => $data){
    $key = array_pop(array_keys($data));
    $value = array_pop(array_values($data));
    $existing[$i][$key] = $value;
}

echo '<pre>'; print_r($existing); echo '</pre>';

PhpFiddle Demo

Sithu
  • 4,752
  • 9
  • 64
  • 110