I would like to compare a barcode which entered by mobileuser from android app to the json url i received from merchant on the server side using php.
Assume this is my mobile user data(hardcoded):
$mobile_card="Card1";
$mobile_code="00004000";
This is the json url i received:
$merchant = file_get_contents('http://localhost/project1/index.php/memberaccount/sendjson');
$decode=json_decode($merchant, true);
There are two row of data in the json url:
[{"merchant_code":"12300000","merchant_contact":"011000000"},
{"merchant_code":"00004000","merchant_contact":"0123456789"}]
This is my code for comparing the $mobile_code to the $merchant_code:
foreach ($decode as $d)
{
$merchantCode = $d['merchant_code'];
if ($merchantCode == $mobile_code)
{
$response["success"] = 1;
$response["message"] = "code Exists.";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "code NOT Exists";
echo json_encode($response);
}
}
}
This is output i get:
{"success":0,"message":"Code NOT exists"}
{"success":1,"message":"Code Exists."}
However, I just want the output to be just one line, in this case, the code exists in second row, So I just want the result to show the success and existed result. (showing "Barcode existed" only)
I do not want the unsuccessful result. Anyone can help? Thank you !
Try it like that :
foreach ($decode as $d)
{
$merchantCode = $d['merchant_code'];
if ($merchantCode == $mobile_code)
{
$response["success"] = 1;
$response["message"] = "code Exists.";
echo json_encode($response);
die();
}
}
$response["success"] = 0;
$response["message"] = "code NOT Exists";
echo json_encode($response);
Or if you want to be a bit more elegant (using die()
is not very nice), encapsulate the code inside a function :
function lookupMerchantCode($merchants, $code)
{
foreach ($merchants as $merchant)
{
$merchantCode = $merchant['merchant_code'];
if ($merchantCode == $code)
{
return true;
}
}
return false;
}
$result = lookupMerchantCode($decode, $mobile_code);
if ($result)
{
echo json_encode(array('success' => 1, 'message' => 'code Exists'));
}
else
{
echo json_encode(array('success' => 0, 'message' => 'code NOT Exists'));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.