简体   繁体   中英

Delete by value in multidimensional array php with no foreach

I'm looping an array like this:

[0] => stdClass Object
    (
        [codigo] => 1
        [producto] => coche
    )

[1] => stdClass Object
    (
        [codigo] => 2
        [producto] => coche
    )

[2] => stdClass Object
    (
        [codigo] => 3
        [producto] => casa
    )

[3] => stdClass Object
    (
        [codigo] => 4
        [producto] => Avion

    )
[4] => stdClass Object
    (
        [codigo] => 5
        [producto] => casa
    )

I have the foreach, that´s okey, but now, i want that when i find a value like 'casa', delete all elements with that value. Then the array looping will be smaller. Then when i find the next value 'coche' delete all the elements with that name, and do that till find all values. Thats because a lot of elements with same values, and not to loop all the time, i could unset this elements when find.

Its like first time i find the value coche, array looks like:

[2] => stdClass Object
    (
        [codigo] => 3
        [producto] => casa
    )

[3] => stdClass Object
    (
        [codigo] => 4
        [producto] => Avion

    )
[4] => stdClass Object
    (
        [codigo] => 5
        [producto] => casa
    )

I have this:

foreach ($products as $key => $value) {
    if(value == 'coche') $coche = 1;
    //inside this if, i just want to delete from product's all elements with 
    // value coche, but i don't want to use another foreach, because is a 
    // non sense, it must be with a function.
}

You can use array_filter for this:

<?php
    $elements = [
        0 => [
            'codigo' => 1,
            'producto' => 'coche'
        ],

        1 => [
            'codigo' => 2,
            'producto' => 'coche'
        ],
        2 => [
            'codigo' => 3,
            'producto' => 'casa'
        ],
        3 => [
            'codigo' => 4,
            'producto' => 'Avion'
        ],
        4 => [
            'codigo' => 5,
            'producto' => 'casa'
        ]
    ];

    $els = array_filter($elements, function($el)
    {
        return ($el['producto'] !== 'casa');
    });

    echo '<pre>'. print_r($els, 1) .'</pre>';

Here I use arrays, so just replace this line:

return ($el['producto'] !== 'casa');

with:

return ($el->producto !== 'casa');

and it'll work for your code.

Essentially we return all elements in the array where producto doesn't equal casa.

Then you can loop only the elements you want. You could also do though inside your foreach:

foreach ($elements as $el)
{
    if ($el->producto == 'casa') {continue;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM