N
N
nictur18172021-12-15 22:58:18
PHP
nictur1817, 2021-12-15 22:58:18

How to remove an array from a multidimensional array by key in a foreach loop?

There is an array. In it, arrays containing fbo and fbs can be located in different orders [0] or [1]:

Array (
[0] => Array (
    [product_id] => 111
    [offer_id] => AR-001
    [stocks] => Array (
        [0] => Array (
            [type] => fbo
            [present] => 0
            [reserved] => 0
            )
        [1] => Array (
            [type] => fbs
            [present] => 10
            [reserved] => 0
            )
        )
    )
[1] => Array (
    [product_id] => 222
    [offer_id] => AR-002
    [stocks] => Array (
        [0] => Array (
            [type] => fbs
            [present] => 0
            [reserved] => 0
            )
        [1] => Array (
            [type] => fbo
            [present] => 20
            [reserved] => 0
            )
        )
    )
)


In the foreach loop, I want to delete the internal arrays where there is fbo. So that the output is an array containing only fbs. Like this:

Array (
[0] => Array (
    [product_id] => 111
    [offer_id] => AR-001
    [stocks] => Array (
        [0] => Array (
            [type] => fbs
            [present] => 10
            [reserved] => 0
            )
        )
    )
[1] => Array (
    [product_id] => 222
    [offer_id] => AR-002
    [stocks] => Array (
        [0] => Array (
            [type] => fbs
            [present] => 0
            [reserved] => 0
            )
         )
    )
)


I try like this:
foreach ($items as $k => $v) {
  if ($v['stocks']['type'] == 'fbo') {
        unset($items[$k]);
    }

Not removed. Already broke my head.

How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2021-12-16
@nictur1817

If there's a chance that the stocks key won't be in place, don't forget to add an appropriate check.
Similarly with type

foreach ($items as $itemIndex=>$item) {
    foreach($item['stocks'] as $stockIndex=>$stock) {
        if ($stock['type'] === "fbo") {
            unset($items[$itemIndex]['stocks'][$stockIndex]);
            $items[$itemIndex]['stocks'] = array_values($items[$itemIndex]['stocks']);
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question