i have a simple json array. in which i have two objects. now i am checking it for some specific values , if found do some thing , if not found do another thing. But i dont know why if condition runs both blocks. true and false both blocks are executed. please help.
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring);
$count = count($jsonarr->like);
for ($r = 0; $r < $count; $r++)
{
if ($jsonarr->like[$r]->username == 'abc' && $jsonarr->like[$r]->password == 'abc')
{
echo 'Match';
}else
{
echo 'No Match';
}
}
is it not like regular if condition ?
答案 0 :(得分:2)
It's showing both blocks because you are looping thru the json array which contains two items. One matching your condition, the other not matching. Here is a simpler version that does not use a loop but just tests your value if in the array. Notice the 'true' flag in the json_decode as well.
<?php
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring, true);
$testArray = $jsonarr['like'];
$loginArray = array('username'=>'abc','password'=>'abc');
if (in_array($loginArray,$testArray)) {
echo 'match found, do login';
} else {
echo "no match, do something else";
}
?>