1

I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.

It might be best if I show to you

foreach ($fields as $f)
{  
    if ($f == 'Thumbnail')
    {
        $thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
        array_push($newrow, $thumnail);
    }
    else
    { 
        $newrow[$f] = $row[$f];
    }
}

The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .

Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.

 array(4) { ["Product ID"]=> string(7) "1007520"
           ["SKU"]=> string(5) "G1505"
           ["Name"]=> string(22) "150mm Oval Scale Ruler"            
           array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }

I would really appreciate any advice.

hdvianna
  • 443
  • 5
  • 13
andreea115
  • 289
  • 1
  • 3
  • 14
  • possible duplicate of [How to push both value and key into array with php](http://stackoverflow.com/a/2926547/476) – deceze Jul 30 '13 at 11:57

3 Answers3

2

You can use array_merge function

$newrow = array_merge($newrow, $thumnail);
Bora
  • 10,529
  • 5
  • 43
  • 73
2

All you really want is:

$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
deceze
  • 510,633
  • 85
  • 743
  • 889
  • thank you everyone for your kind help. i guess i was a little confused about how the arrays work. the solution provided by deceze and xdim222 was correct. thank you everyone for your kind help – andreea115 Jul 30 '13 at 12:47
1

Alternatively, you can also assign it directly to $newrow:

if ($f == 'Thumbnail')
  $newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...

Or if you want your code to be shorter:

foreach($fields as $f)
  $newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];

But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k

xdim222
  • 453
  • 1
  • 5
  • 10
  • hi everyone. array_merge only works from php 5.4; i am required to use php 5.3. I also cannot use the solution posted by xdim222 because i need to place the array 'key and value' within the new $newrow array. Does anyone have any advice – andreea115 Jul 30 '13 at 12:13
  • 1
    @andreea115 array_merge is from PHP 4. However, there is a difference in the function signature between versions 4 and 5. Since PHP version 5 the array_merge accepts only arrays. See: http://www.php.net/manual/en/function.array-merge.php#refsect1-function.array-merge-changelog. – hdvianna Jul 30 '13 at 12:19