0

I have this array:

I have this array.

There are many ['variants'] below.

I need to create a new array like this:

new array like this

from all ['variants'].

I have a function with this

$variants = array();
$features = $features['18']; foreach ($features as $feature) {
    if (!empty($feature['variants'])) {
        $variants = array_merge($variants, $feature['variants']);
    }
}
    fn_print_r($variants);
return $variants;

But it have error: array_merge() [function.array-merge]: Argument #2 is not an array.

How can I fix this?

5
  • Please include your arrays inside your question. Also where do you have a key 18? And what exactly is in $features before you loop over it? Commented Aug 30, 2016 at 1:54
  • $features['18'] - array like 1-st image Commented Aug 30, 2016 at 1:55
  • Your foreach loop does not make sense then, since you loop over each value and I don't see why you want to merge variants, since you only have it once in your array. Why not just do $variants = $features["variants"];? Commented Aug 30, 2016 at 1:57
  • If i do like this, i have array with old ["variants"] id. Like 197 - 198 ... ect. I need new with id 0,1,2 ect. Commented Aug 30, 2016 at 2:10
  • Then just reindex the array with array_values(), e.g. $variants = array_values($features["variants"]); Commented Aug 30, 2016 at 2:11

1 Answer 1

1

If you code correct - rewrite line 3:

if (!empty($feature['variants'])) {

on:

if (!empty($feature['variants']) && is_array($feature['variants'])) {

And I would give the call to array_values. For example:

foreach($features as $feature)
{
    $result = [];
    if(isset($feature['variants']) && is_array($feature['variants']))
    {
        $result = array_merge($result, array_values($feature['variants']));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.