-5

i have a JSON with this data:

$data = "meta_data":[  
{  
   "id":2279,
   "key":"codice_fiscale",
   "value":"gege"
},
{  
   "id":2280,
   "key":"numero_tessera_titolare",
   "value":"gre"
},
{  
   "id":2281,
   "key":"classe_tessera_titolare",
   "value":"gre"
},
{  
   "id":2282,
   "key":"tratta_da",
   "value":"gre"
},
{  
   "id":2283,
   "key":"tratta_a",
   "value":"grge"
},
{  
   "id":2284,
   "key":"studente",
   "value":"studente"
}];

I need to loop all "key" and when i find the key that i need (in this case "studente") i need to get the value stored in "value".

How can i do this in PHP?

EDIT

I tried this:

foreach($data as $row){
    if($row->key=='studente'){
        $var = $row->value;
    }
}
  • Possible duplicate of [Parsing JSON file with PHP](https://stackoverflow.com/questions/4343596/parsing-json-file-with-php) – reixa Jul 03 '17 at 07:24

2 Answers2

1

The best / most efficient way is to write a foreach loop with a break.

Code: (Demo)

$json = '{
"meta_data": [
{
   "id": 2279,
   "key": "codice_fiscale",
   "value": "gege"
},
{
   "id": 2283,
   "key": "tratta_a",
   "value": "grge"
},
{
   "id": 2284,
   "key": "studente",
   "value": "studente"
}
]}';

$data = json_decode($json, true);
$search='studente';

$found=false;
foreach($data['meta_data'] as $d){
    if($d['key']==$search){
        $found=$d['value'];
        break;
    }
}
echo $found?$found:"$search not found";

Output:

studente
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

First, $data is not a valid json. You can use json_decode() to get a php array representation of your json string. Then loop through array.

Example:

$json = '{
"meta_data": [
{
   "id": 2279,
   "key": "codice_fiscale",
   "value": "gege"
},
// other items...
{
   "id": 2283,
   "key": "tratta_a",
   "value": "grge"
},
{
   "id": 2284,
   "key": "studente",
   "value": "studente"
}
]}';

$data = json_decode($json, true);
//var_dump($data);

foreach($data['meta_data'] as $key => $item) {
  if (isset($item['value']) && $item['value'] == 'studente') {
      var_dump($item);
  }
}
BenRoob
  • 1,662
  • 5
  • 22
  • 24