Tom Chambers
Tom Chambers

Reputation: 374

How do i add values of a certain key from two arrays into one new array in PHP?

I need to amalgamate some notices into an overall array.

   array today = array( 
'keya' => '11',
'keyb' => 'string',
'notice' => 'Visitor Arrives at 3pm',
'keyd' => '44',
...
);

array general = array( 
'keya' => '1',
'notice' => 'Fire Alarms Tested This Week'
);

I want to have a new array called $general_notice which merges the $today['notice'] with $general['notice'].

I can't understand what to do using operators or array_merge as i only one to merge the data of a particular key...

NB $general may have multiple rows ie multiple notices...

I think i cant use array_merge because the arrays are multi-dimensional.

EG:

//1st array with lots of data but the data belonging to the 'notice' key is what i'm interested in.
array $today = [0]('id'=>'1','lotsOfKeys'=>"lots of values,'notice'="Visitor arrives at 3pm");

array $general = [0]('id'=> '1', 'notice' = "Fire Alarms Tested This Week"),
                 [1]('id'=> '2', 'notice' = "Blue Shift working");

The desired result is:

$notices = ("Visitor arrives at 3pm", "Fire Alarms Tested This Week", "Blue Shift Working");

Upvotes: 1

Views: 52

Answers (2)

Ernis
Ernis

Reputation: 676

Since you are using arrays with keys and each array can't have duplicate keys, your desired result would be as simple as:

array general_notice = array($today['notice'], $general['notice']);

unless you have a two dimensional array of arrays, for example:

array general = array(
     array( 
         'keya' => '11',
         'keyb' => 'string',
         'notice' => 'Visitor Arrives at 3pm',
         'keyd' => '44'
      ),
      array( 
          'keya' => '1',
          'notice' => 'Fire Alarms Tested This Week'
      ),
      ...
);

In that case, you would need to loop though the notices array and push desired values to a new one like so. You can repeat the loop for each array you want to append to the general_notice array:

array general_notice = array();
foreach ($general as $value) {
    array_push($general_notice, $value['notice'] );
}

You can also append any single dimensional arrays as follows

array_push($general_notice, $today['notice']);

Upvotes: 2

Tolulope Olufohunsi
Tolulope Olufohunsi

Reputation: 11

The question is unclear, what do you mean by merging them? Are you trying to concatenate the values of the keys based on both arrays having the same key?

Upvotes: 0

Related Questions