I have a array list (for this example I'm using cell phones). I'm wanting to be able to search for multiple key/value pairs and return it's parent array index.
For example, here is my array:
// $list_of_phones (array)
Array
(
[0] => Array
(
[Manufacturer] => Apple
[Model] => iPhone 3G 8GB
[Carrier] => AT&T
)
[1] => Array
(
[Manufacturer] => Motorola
[Model] => Droid X2
[Carrier] => Verizon
)
)
I'm wanting to be able to do something like the following:
// This is not a real function, just used for example purposes
$phone_id = multi_array_search( array('Manufacturer' => 'Motorola', 'Model' => 'Droid X2'), $list_of_phones );
// $phone_id should return '1', as this is the index of the result.
Any ideas or suggestions on how I can or should do this?
The array_keys() function returns an array containing the keys.
PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
Perhaps this will be useful:
/**
* Multi-array search
*
* @param array $array
* @param array $search
* @return array
*/
function multi_array_search($array, $search)
{
// Create the result array
$result = array();
// Iterate over each array element
foreach ($array as $key => $value)
{
// Iterate over each search condition
foreach ($search as $k => $v)
{
// If the array element does not meet the search condition then continue to the next element
if (!isset($value[$k]) || $value[$k] != $v)
{
continue 2;
}
}
// Add the array element's key to the result array
$result[] = $key;
}
// Return the result array
return $result;
}
// Output the result
print_r(multi_array_search($list_of_phones, array()));
// Array ( [0] => 0 [1] => 1 )
// Output the result
print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple')));
// Array ( [0] => 0 )
// Output the result
print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple', 'Model' => 'iPhone 6')));
// Array ( )
As the output shows, this function will return an array of all keys with elements which meet all the search criteria.
you may use array_intersect_key and array_intersect and array_search
check array_intersect_key php manual to get array of items with matching keys
and array_intesect php manual to get array if items with matching values
u can get value of key in array using $array[key]
and get key of value in array using array_search $key = array_search('green', $array);
php.net/manual/en/function.array-search.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With