PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 15, 2022

[FIXED] Check if data is in array in PHP

 March 15, 2022     codeigniter, json, php     No comments   

Issue

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.


Solution

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);


Answered By - Nero
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing