Check if there is a value in JSON with PHP

1

I have a variable that returns a certain number that is correct.

Example:

$cc = "52532005536430673";

My question is: how do I check if this number is present in a JSON? As below:

{
    "testadas": {
        "52532005536430673|04|2023|869": {
            "cc": "52532005536430673",
            "dados": "\ud83c\udde7\ud83c\uddf7",
            "status": "Reprovada",
            "data_hora": "02-09-2018 20:45:13",
            "retestada": false
        }
    }
}

In this case it is present in the "CC" and I always want to check if the number is present in the "CC".

    
asked by anonymous 03.09.2018 / 01:49

2 answers

0

Basically, you can convert this json to an object or array, and then cycle through all of the items that are in the "tested" by checking if the cc field is not empty.

In the example below, I converted json to array, using the json_decode function, and passed json as the first parameter and the second value 1, which indicates that I want to convert to array instead of object.

$json = '{
"testadas": {
    "52532005536430673|04|2023|869": {
        "cc": "52532005536430673",
        "dados": "\ud83c\udde7\ud83c\uddf7",
        "status": "Reprovada",
        "data_hora": "02-09-2018 20:45:13",
        "retestada": false
    }
  }
}';

$resultado_json = json_decode($json,1);
$cartao = "52532005536430673";
foreach($resultado_json["testadas"] as $item){
  if($item["cc"] == $cartao){
    print "Numero presente no campo cc";
  }
}
    
03.09.2018 / 02:06
0

Here is the working code, it takes the cc from JSON and then compares it with the value of the variable. To get an external file, you must use file_get_contents() to get the JSON link:

PHP File:

<?php
$cc = "52532005536430673";
$file = "ccs.json";

$json_file = file_get_contents($file);
$json_result = json_decode($json_file);

foreach($json_result->testadas as $item){
    if($item->cc == $cc){
        print "Esse número está presente em cc";
    }
    else{
        print "Esse número não está presente em cc";
    }
}
?>

ccs.json

{
    "testadas": {
        "52532005536430673|04|2023|869": {
            "cc": "52532005536430673",
            "dados": "\ud83c\udde7\ud83c\uddf7",
            "status": "Reprovada",
            "data_hora": "02-09-2018 20:45:13",
            "retestada": false
        }
    }
}
    
03.09.2018 / 02:15