B
B
Boris2021-03-29 11:26:22
PHP
Boris, 2021-03-29 11:26:22

How to delete an array within an array by a specific value?

I have an array like this:

$results = [ 
         ['order_id'  =>  'first',  'id'=> 1],
         ['order_id'  =>  'second',   'id'=> 4],
         ['order_id'  =>  'third',   'id'=> 7]
    ];

//Прогоняю в цикле с условием, что будет удален подмассив в котором 'id' равен 4.

foreach ($results as $item){
       foreach ($item as $value){
        }
        if ($item['id'] == 4)
        unset($item);
}
print_r ($results);


However, after all that I did, the array remains unchanged.
Even though ['order_id' => 'second', 'id'=> 4]he had to leave.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2021-03-29
@BorisFX107

a normal answer to this question
, otherwise right now they will come running with links, or out - filters with a subvert.

foreach ($results as $key => $item) {
    if ($item['id'] === 4) {
        unset($results[$key]);
    }
}

S
Slava Rozhnev, 2021-03-29
@rozhnev

Using array_filter:

<?php
$results = [
  ['order_id' => 'first', 'id'=>1],
  ['order_id' => 'second', 'id'=>4],
  ['order_id' => 'third', 'id'=>7]
];

$filtered = array_filter(
  $results,
  function($el) {
    return $el['id'] != 4;
  }
);

var_export($filtered);

Share PHP code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question