sleakerz
sleakerz

Reputation: 169

How to insert a row of array into another array

Data is coming from 2 differents SQL request, so i have 2 arrays like :

FIRST ARRAY
array(6) {
  [0]=>
  array(2) {
    ["edible"]=>
    string(3) "600"
    ["Food"]=>
    string(4) "Fruit"
  }
  [1]=>
  array(2) {
    ["edible"]=>
    string(3) "500"
    ["Food"]=>
    string(6) "Vegetables"
  }
  [2]=>
  array(2) {
    ["edible"]=>
    string(4) "1000"
    ["Food"]=>
    string(3) "meat"
  }
  ...


 SECOND ARRAY
array(5) {
  [0]=>
  array(2) {
    ["out-of-date"]=>
    string(3) "17"
    ["Food"]=>
    string(4) "Fruit"
  }
  [1]=>
  array(2) {
    ["out-of-date"]=>
    string(3) "54"
    ["Food"]=>
    string(3) "Vegetables"
  }
  [2]=>
  array(2) {
    ["out-of-date"]=>
    string(2) "60"
    ["Food"]=>
    string(3) "meat"
  }
 ...  

What i would like is to merge the two arrays, but not with a function like array_merge or array_merge_recursive. Because i would like to just add a row (key + value) like

["out-of-date"]=>
    string(3) "17""

in the first array if we have the same Food (key)

output result desired :

array(6) {
  [0]=>
  array(3) {
    ["out-of-date"]=>
    string(3) "17"
    ["edible"]=>
    string(3) "600"
    ["Food"]=>
    string(4) "Fruit"
  }
...

Upvotes: 0

Views: 465

Answers (2)

marv255
marv255

Reputation: 818

I'm not sure about structure of your database table. But let's you have two tables in your MySql database:

First - edible | Food

Second - out_of_date | Food

So you can query your array by using join mysql operation. You need sql like below:

SELECT * 
FROM First
LEFT JOIN Second ON First.Food=Second.Food

Also, you can use additional conditions for all tables like:

SELECT * 
FROM First
LEFT JOIN Second ON First.Food=Second.Food
WHERE First.edible = 1000 AND Second.out_of_date = 10

You can find more information here: http://dev.mysql.com/doc/refman/5.7/en/join.html

Upvotes: 1

Jorge Hess
Jorge Hess

Reputation: 550

You need to make a loop inside loop and verify the food key, if is equal merge the values to another array, Try this code:

<?php

$array1 = array();

$array1[] = array('food' => 'Fruit', 'edible' => '600');
$array1[] = array('food' => 'Vegetables', 'edible' => '500');
$array1[] = array('food' => 'meat', 'edible' => '700');

$array2 = array();
$array2[] = array('food' => 'Fruit', 'out-of-date' => '17');
$array2[] = array('food' => 'Vegetables', 'out-of-date' => '15');

$array_merged = array();


foreach ($array1 as $key => $value) {
    $array_merged[$key] = $value;
    foreach ($array2 as $ke => $val) {
        if ($val['food'] == $value['food']) {
            $array_merged[$key]['out-of-date'] = $val['out-of-date'];
        }
    }
}

print_r($array_merged);

Upvotes: 1

Related Questions