When manipulating multidimensional arrays, it's often necessary to locate a specific key based on a corresponding value. This task can be accomplished using various techniques in PHP.
To utilize this approach, you'll need to ensure you're using PHP version 5.5.0 or higher.
$key = array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));
Explanation:
function array_search_multidim($array, $column, $key) { $result = null; array_walk_recursive($array, function ($value, $index) use ($column, $key, &$result) { if ($index === $column && $value === $key) { $result = $index; } }); return $result; } $key = array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');
Explanation:
The array_search() and array_column() approach generally offers better performance compared to the array_walk_recursive() method. However, both techniques are suitable for most applications, and the specific choice will depend on individual requirements.
The above is the detailed content of How to Efficiently Search for a Value in a PHP Multidimensional Array?. For more information, please follow other related articles on the PHP Chinese website!