0

I have a little problem with a simple loop. I have a data like this :

$PRODUCT = [

'title' => 'Blouse',
'lines' => [

    'variants' => [
        [
            'price' => 112.34,
            'options' => [
                'size' => 'small',
                'color' => 'yellow',

            ]
        ],
        [
            'price' => 156.33,
            'options' => [
                'size' => 'small',
                'color' => 'blue',

            ]
        ],
    ],
  ]

I need to create a new table like this:

$options => [
        'size',
        'color'
    ]

I'm trying to get only to array with key 'options' in my loop, and I even have data which I need, but I have warning:

Warning: Illegal string offset 'options'

My loop looks like this:

$options = [];

foreach ($PRODUCT['lines'] as $variant){
    foreach ($variant as $item) {
      $options[] = $item['options'];
    }
 }

Where is my mistake? I know that 'price' is not an array, but what does to have no warnings in this case?

2 Answers 2

5

You miss a level in your array. Try this :

$options = [];

foreach ($PRODUCT['lines']['variants'] as $variant){
    foreach ($variant as $item) {
      $options[] = $item['options'];
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

3

You can use array_column.

$options = array_column($PRODUCT['lines']['variants'], 'options');
var_dump($options);

Array_column will get all array items called 'options' and save them to the $options variable.

https://3v4l.org/bJKX4

Comments

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.