<?php
if ( ! function_exists('subarray_element'))
{
/**
* Gets the sub-array containing a value of certain key present in it
*
* @param array $arr contains arrays with key => val pairs
* @param string $id_key key of the subarray to filter
* @param string $id_val value of the corresponding key
* @return first element matching the value provided or FALSE
* @link https://stackoverflow.com/q/13933454/6225838
* @author CPHPython
*/
function subarray_element($arr, $id_key, $id_val = NULL) {
return current(array_filter(
$arr,
function ($subarr) use($id_key, $id_val) {
if(array_key_exists($id_key, $subarr))
return $subarr[$id_key] == $id_val;
}
));
}
}
$list = [
[
'id' => '3243',
'link' => 'fruits',
'lev' => '1',
],
[
'id' => '6546',
'link' => 'apple',
'lev' => '2',
],
[
'id' => '9348',
'link' => 'orange',
'lev' => '2',
],
[
'id' => '9000',
'link' => 'orange',
'lev' => '2',
]
];
echo 'Matching pair: '.var_export(subarray_element($list, 'id', 9348), TRUE).PHP_EOL.'-------'.PHP_EOL.
'Non-matching pair: '.var_export(subarray_element($list, 'id', 42), TRUE).PHP_EOL.'-------'.PHP_EOL.
'Duplicate pair: '.var_export(subarray_element($list, 'link', 'orange'), TRUE).PHP_EOL.'-------'.PHP_EOL;
usort($list, function($f1, $f2){ return $f1['id'] > $f2['id']; });
echo 'Duplicate pair after sortind by id: '.var_export(subarray_element($list, 'link', 'orange'), TRUE);
preferences:
28.61 ms | 402 KiB | 5 Q