Maison >développement back-end >tutoriel php >Comment supprimer des éléments de tableau multidimensionnel par valeur en PHP ?
Deleting Elements from a Multidimensional Array Based on Value
In PHP, working with multidimensional arrays often presents the need to remove specific elements based on their values. Here's how you can approach this challenge:
Solution:
To remove elements from a multidimensional array based on a value, you can use the following function:
<code class="php">function removeElementWithValue($array, $key, $value) { foreach ($array as $subKey => $subArray) { if ($subArray[$key] == $value) { unset($array[$subKey]); } } return $array; }</code>
Usage:
To utilize this function, you simply need to pass in the array, the key of the element you want to match, and the value to match. For example, in your case, you would call the function like this:
<code class="php">$array = removeElementWithValue($array, "year", 2011);</code>
This will remove any sub-arrays where the "year" key has the value "2011" from the given array.
Output:
After executing the above function call, your array will look like this:
Array ( [0] => Array ( [filmId] => 68593 [url] => http://www.moviemeter.nl/film/68593 [title] => Unstoppable [alternative_title] => [year] => 2010 [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/68000/68593.jpg [average] => 3.3 [votes_count] => 191 [similarity] => 100.00 [directors_text] => geregisseerd door Tony Scott [actors_text] => met Denzel Washington, Chris Pine en Rosario Dawson [genres_text] => Actie / Thriller [duration] => 98 ) [1] => Array ( [filmId] => 17931 [url] => http://www.moviemeter.nl/film/17931 [title] => Unstoppable [alternative_title] => Nine Lives [year] => 2004 [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/17000/17931.jpg [average] => 2.64 [votes_count] => 237 [similarity] => 100.00 [directors_text] => geregisseerd door David Carson [actors_text] => met Wesley Snipes, Jacqueline Obradors en Mark Sheppard [genres_text] => Actie / Thriller [duration] => 96 ) )
The sub-arrays with "year" equal to "2011" have been successfully removed.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!