Skip to content
Advertisement

Check if data is in array in PHP [closed]

Using Codeigniter 3 I need to compare two json object. To explain better, below the json data I have to check:

[
    {
        "id":23456,
        "name":"Some data"
    },
    {
        "id":98765,
        "name":"Other data"
    },
    {
        "id":12345,
        "name":"A glider"
    },
    {
        "id":34567,
        "name":"Other aircraft"
    }
]

I need to compare the above data with the following json object.

[
    {
        "id":23456,
        "name":"Some data",
        "available": 0,
    },
    {
        "id":98765,
        "name":"Other data",
        "available": 1,
    },
    {
        "id":12345,
        "name":"A glider",
        "available": 0,
    },
    {
        "id":34567,
        "name":"Other aircraft",
        "available": 0,
    },
    {
        "id":56789,
        "name":"Dummy aircraft",
        "available": 0,
    },
]

I have to select data from the first json object that compare in the secon one with “available” field equal to 1.

Hope the edited my question, I hope is now clear. My apologize for my bad english.

Advertisement

Answer

Try this :

$data = json_decode('[
    {
        "id":23456,
        "name":"Some data"
    },
    {
        "id":98765,
        "name":"Other data"
    },
    {
        "id":12345,
        "name":"A glider"
    },
    {
        "id":34567,
        "name":"Other aircraft"
    }
]');
for ($i = 0; $i < count($data); $i++) {
     if (property_exists($data[$i], 'id') && property_exists($data[$i], 'name')){
         $data[$i]->available = 1 ;
     }else{
         $data[$i]->available = 0;
     }
}
var_dump($data);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement