Maison > Article > développement back-end > Comment supprimer des éléments des tableaux multidimensionnels en fonction d'une valeur clé spécifique ?
Removing Elements from Multidimensional Arrays Based on Value
In various programming scenarios, the need arises to remove specific elements from multidimensional arrays based on certain criteria. This article addresses the case where you encounter an array with sub-arrays containing a key-value pair, and you aim to delete sub-arrays whose key matches a given value.
Consider the following multidimensional array as an example:
Array ( [0] => Array ( [year] => 2011 ) [1] => Array ( [year] => 2011 ) [2] => Array ( [year] => 2010 ) [3] => Array ( [year] => 2004 ) )
In this array, we want to delete all sub-arrays where the 'year' key equals 2011.
To achieve this, PHP 5.2 provides the following function:
function removeElementWithValue($array, $key, $value){ foreach ($array as $subKey => $subArray) { if ($subArray[$key] == $value) { unset($array[$subKey]); } } return $array; }
By invoking this function as follows:
$array = removeElementWithValue($array, "year", 2011);
The resulting array will contain only the sub-arrays with 'year' values other than 2011:
Array ( [0] => Array ( [year] => 2010 ) [1] => Array ( [year] => 2004 ) )
This approach efficiently filters out sub-arrays based on specific value criteria from multidimensional arrays.
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!