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.

1

3 Answers 3

2

All you really want is:

$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

You can use array_merge function

$newrow = array_merge($newrow, $thumnail);

Comments

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

2 Comments

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 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: php.net/manual/en/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.