dtny30176 2017-09-18 13:14
浏览 239
已采纳

检查json foreach循环中是否存在字符串

I am trying to check if a value exists inside an foreach loop from a decoded json response and compare it to my own string. I need to set $response_array['status'] to "Allowed" if $domain_to_check value exists inside the $key_info['registered_domain'] array. I tried to use in_array php function to check if value exists, however i had no success and i keep getting back "Not Allowed - Domain not listed" response even when the value is inside the array. I think that the problem is with my foreach loop but for the sake of me i can't figure whats wrong.

$domain_to_check = 'domain-name.com';
$data = json_decode($returnCheckValue,true);
$key_response = $data['result'];
if ($key_response == 'success'){
    foreach ($data['registered_domains'] as $key_domain_info) {
        $key_listed_domain = $key_domain_info['registered_domain'];
        if ($key_response == 'success' && in_array($domain_to_check, $key_listed_domain)) {
            $response_array['status'] = 'Allowed';
        }
        else {
            $response_array['status'] = 'Not Allowed - Domain not listed';
        }
    }
}
else {
    $response_array['status'] = 'Not Allowed - Wrong Key';
}
echo json_encode($response_array);

Here is how my var_dump(); of the $data looks like

array(9) { ["result"]=> string(7) "success" ["max_allowed_domains"]=> string(1) "3" ["registered_domains"]=> array(2) { [0]=> array(5) { ["id"]=> string(2) "60" ["lic_key_id"]=> string(2) "51" ["lic_key"]=> string(13) "93248cqkdj21as" ["registered_domain"]=> string(19) "domain-name-2.com" ["item_reference"]=> string(1) "1" } [1]=> array(5) { ["id"]=> string(2) "58" ["lic_key_id"]=> string(2) "51" ["lic_key"]=> string(13) "93248cqkdj21as" ["registered_domain"]=> string(14) "domain-name.com" ["item_reference"]=> string(3) "443" } } }
  • 写回答

2条回答 默认 最新

  • duanlangwen9597 2017-09-18 14:22
    关注

    Relate below code with your code. This code is working.

        $domain_to_check = "domain-name.com";
    
        $test = array("registered_domains" => array("registered_domain" => "domain-name-2.com"), array("registered_domain" => "domain-name.com"));
    
        foreach($test as $val) {
            if($val['registered_domain'] == $domain_to_check) {
                $result = 'success';
                break;
    
            } else {
                $result = 'failure';
            }
        }
    
        echo $result;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭