2

I got multidimensional array.

From each subarray, I would like to remove / unset values with price more than 1500.

Array

$item = array(
    'phone' => array(
        array(
            'Item' => 'S5',
            'info' => array(
                array('seller' => 'John', 'price' => 1800),
                array('seller' => 'Mason','price' => 1200),
                array('seller' => 'Alex','price' => 1500),
            ),
        ),
        array(
            'Item' => 'iPhone 5',
            'info' => array(
                array('seller' => 'Depay', 'price' => 1900),
                array('seller' => 'David', 'price' => 1450),
                array('seller' => 'Daemon', 'price' => 1600),
            )
        ),
    ),
);

my code:

foreach($item['phone'] as $key =>$price)
{
    foreach($price['info'] as $info => $price2 )
    {
        if ($info['price'] >= 1500)
        {
            unset($item[$key][$info ]);

        }
    }
}

Why this code does not work? Can this be done? and if yes... How???

Thanks in advance :-)

2 Answers 2

1

You referring to the wrong element level:

foreach($item['phone'] as $key =>$price)
{
    foreach($price['info'] as $info => $price2 ) // $price2
    {
        if ($info['price'] >= 1500) // should be $price2
        {
            unset($item[$key][$info ]);

        }
    }
}

You should point into $price2 in your condition:

if ($price2['price'] >= 1500) {

Then, on unsetting, you'll need to point/walk into indices

// write the complete address of this element you want to unset
unset($item['phone'][$key]['info'][$info]); 
//             ^              ^   don't forget this since they are part of the structure

So all in all:

foreach($item['phone'] as $key =>$price)
{
    foreach($price['info'] as $info => $price2 )
    {
        if ($price2['price'] >= 1500) {
            unset($item['phone'][$key]['info'][$info]);
        }
    }
}

Sample Output

Sign up to request clarification or add additional context in comments.

Comments

0

Your code should be like

foreach($item['phone'] as $key => $price) {

    foreach($price['info'] as $info => $price2 ) {

        if ($price2['price'] >= 1500) {

            unset($item['phone'][$key]['info'][$info]); 

        }
    }
}

In if condition you are using key $info, it should be $price2.

Here is the running code https://ideone.com/Mk7VfU

1 Comment

Agreed $info should be $price2 however this still doesn't unset items with prices equal or above 1500

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.