worldEdit
worldEdit

Reputation: 43

Get Matching entry in array using php

I need to get a special entry from a json array and it should be matched by id.

{
            "response": {
                "count": 62,
                "inventory": [
                    {
                        "id": 10,
                        "style": 982
                    },
                    {
                        "id": 20,
                        "style": 0
                    },
                    {
                        "id": 30,
                        "style": 1
                    }       ]
    }}

Everything I have right now is this code:

$matching_value = 10;    
foreach($json_data as $key => $val){
    if($val->id == $matching_value){
      echo $val->id;
      echo $val->style;
       }
    }

But it is not working and I don't know why. Does my approach not work with sub-entries?

Upvotes: 1

Views: 485

Answers (1)

Jens A. Koch
Jens A. Koch

Reputation: 41776

Here you go.

  • you need to decode the json string to an array
  • inside the foreach, you have used object property access syntax and i've changed that to array access ($val->id ... $val['id'])

Does my approach not work with sub-entries?

Not like you have it. You would have to test what you are iterating over, if its a string, int, array. Consider the nesting, etc. I have reassigned $inventory to make iterating over the inner array a bit easier, gets you closer to the value

Source:

// JSON string
$json = '{
    "response": {
        "count": 62,
        "inventory": [
            {
                "id": 10,
                "style": 982
            },
            {
                "id": 20,
                "style": 0
            },
            {
                "id": 30,
                "style": 1
            }
        ]
    }}
';

// debugging
var_dump($json, json_decode($json, true));

// decode json to array
$data = json_decode($json, true);

// prepare iteration

// reassign 
$inventory = $data['response']['inventory'];

$matching_value = 10;

foreach($inventory as $key => $val)
{
    //var_dump($val);

    if(isset($val['id']) && $val['id'] === $matching_value)
    {
      echo 'The ID: ' . $val['id'];
      echo 'The Style' . $val['style'];
    }
}

Output: The ID: 10The Style982

Upvotes: 1

Related Questions