I have a multidimensional array with following values
$array = array(
0 => array (
\"id\" => 1,
\"parent_id\" =&
You could implement it using array_filter
, to filter the array down to the elements that match a given parent id, and then return the count
of the filtered array. The filter is provided a callback, which is run over each element of the given array.
function find_children($array, $parent) {
return count(array_filter($array, function ($e) use ($parent) {
return $e['parent_id'] === $parent;
}));
}
find_children($array, 1); // 2
find_children($array, 3); // 1
find_children($array, 10); // 0
Whether or not you prefer this to a loop is a matter of taste.
You can use count with array_filter
function doSearch($id, array $array) {
$arr = array_filter($array, function ($var) use ($id){
if ($id === $var['parent_id']) {
return true;
}
});
return count($arr);
}
or shorter version
function doSearch($id, array $array) {
return count(array_filter($array, function($var) use ($id) {
return $id === $var['parent_id'];
}));
}
So basically it gets elements where $id is equal to parent_id and returns their count