[英]Check if associative array contains value, and retrieve key / position in array
[英]check associative array contains value
Array (
[0] => Array (
[questionID] => 47
[surveyID] => 51
[userID] => 31
[question_Title] => Choose Any One?
[question_Type] => Dropdown
[response] => 1.Android 2.Windows 3.Blackberry
[required] => 0
[add_time] => 0
)
[1] => Array (
[questionID] => 48
[surveyID] => 51
[userID] => 31
[question_Title] => Is it?
[question_Type] => Bigbox
[response] => Yes No
[required] => 1
[add_time] => 0
)
[2] => Array (
[questionID] => 129
[surveyID] => 51
[userID] => 31
[question_Title] => sELECT
[question_Type] => Single
[response] => DFG HBK GHCK HK
[required] => 0
[add_time] => 0
)
)
這是我的多維
現在我想最初檢查數組是否包含[required] => 1或[required] => 0
我不想遍歷數組
假設您的陣列名稱為$myarray
所以你可以做這樣的事情-
foreach($myarray as $arrelement)
{
if(isset($arrelement[required]) && $arrelement[required] == 1) //choose 1 or 0 in code as per your need
{
//traverse your array and do needful
}
}
if($yourArr[0]['required']==0) //Just check for first element in your array
echo "Zero";
else
echo "One";
foreach($mainarray as $array ){ //check for each
if($array['required']==1)
//doSome Task
if($array['required']==0)
這可能是今早我將要提出的最駭人聽聞的解決方案,但是如果您要拍攝一線快車,則應該這樣做:
if(in_array(1, array_column($myArray, 'required')))
echo 'required';
編輯:這假設您手邊有PHP 5.5以上
更新:仔細查看in_array()
的文檔后,應該可以這樣:
if(in_array(array('required' => 1), $myArray))
echo 'required';
另一種選擇是,我的方式獨立於數組結構(假設$ x保存您的數據結構):
if (preg_match('/"required":[01]/',json_encode($x))) {
// The array structure contains "required" => 0 or "required" => 1
} else {
// Negative
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.