Search code examples
phpmultidimensional-arrayarray-key

array_push to a multidimensional array if array_key_exists


I am creating a new array ($Parts) from an existing array ($newarray), and reordering the array. However if the array key exists in the new array, I want to append to the 'location' and 'qty' arrays. Here is what the new array structure looks like:

     '4117-0171-249' => 
          'pri_id' => '859'
          'vendor' => 'R01298'
          'score' =>  '0.00'
          'location' => 
                 0 =>  '10103'
           'qty' => 
                 0 =>  '70' 

Here is my code I am using.

$Parts = array();
foreach($newarray AS $Ke => $Va) {
    if(array_key_exists($Va['part_number'], $Parts)){
         array_push($Parts[$location][],$Va['location']);
    } else {
    $Parts[$Va['part_number']] = array('pri_id' => $Va['pri_id'],
                                       'vendor' => $Va['vendor'],
                                       'score' => $Va['Score'],
                                          'location' => array($Va['location']),
                                          'qty' => array($Va['qty']),
                                        );
    }
 }

Solution

  • If anyone stumbles across this in the future, the answer was this:

    $Parts[$Va['part_number']]['location'][] = $Va['location'];