检查是否存在值,并返回多维数组中的对象
问题描述:
我需要检查值是否存在于数组中,一旦存在,我需要获取该对象。检查是否存在值,并返回多维数组中的对象
Array
(
[0] => Array
(
[_id] => Array
(
[purok] => test
[year] => 2017
[options] => below-1
)
[data] => Array
(
[58cf4935572d6e32900057ab] => Array
(
[age-sex-distribution] => Array
(
[age-range] => Array
(
[options] => below-1
)
[gender] => Array
(
[male-distribution-count] => 12
[female-distribution-count] => 12
)
)
)
)
[date] => 2017-07-08
)
[1] => Array
(
[_id] => Array
(
[purok] => test
[year] => 2017
[options] => toddlers (1-2)
)
[data] => Array
(
[58cf4935572d6e32900057ab12] => Array
(
[age-sex-distribution] => Array
(
[age-range] => Array
(
[options] => toddlers (1-2)
)
[gender] => Array
(
[male-distribution-count] => 12
[female-distribution-count] => 12
)
)
)
)
[date] => 2017-07-08
)
)
如果存在,我需要检查这个[options] => below-1
。其中一个存在,我需要在阵列中获得data
。
到目前为止,我已经尝试过这一个。
$keySearch = "data.options";
$dataOption = array_search("below-1", array_column($rec, $keySearch));
print_r($dataOption);
但没有结果。
感谢您提前帮助我。
答
$temp = [];
for ($data as $value){
if($value['_id']['options'] == 'below-1'){
$temp[] = $value;
}
}
print_r($temp);
你可以试试这个
答
试试这个:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
if(!search_array($value, $array)) {
// do something if the given value does not exist in the array
}else{
// do something if the given value exists in the array
}
答
你应该试试这个:
for($i=0; $i < count($rec); $i++) {
if ($rec[$i]['_id']['options'] === "below-1") {
$dataOption = $rec[$i]['data'];
break;
}
}
print_r($dataOption);
它应该做你期待什么;-)