Kim
Kim

Reputation: 1148

Get value in PHP from JSON

I need to get the objects information for "label", "name" where value=true in a PHP variable and not were value=false.

How is this done with this JSON array?

If I make a var_dump of the JSON I get this:

array(8) {
  [0]=>
  object(stdClass)#8 (3) {
    ["label"]=>
    string(4) "Name"
    ["name"]=>
    string(7) "txtName"
    ["value"]=>
    bool(true)
  }
  [1]=>
  object(stdClass)#9 (3) {
    ["label"]=>
    string(6) "E-mail"
    ["name"]=>
    string(8) "txtEmail"
    ["value"]=>
    bool(true)
  }
   [2]=>
  object(stdClass)#10 (3) {
    ["label"]=>
    string(12) "Phone Number"
    ["name"]=>
    string(8) "txtPhone"
    ["value"]=>
    bool(false)
  }
  [3]=>
  object(stdClass)#11 (3) {
    ["label"]=>
    string(19) "Mobile Phone Number"
    ["name"]=>
    string(14) "txtMobilePhone"
    ["value"]=>
    bool(false)
  }
}

Upvotes: 0

Views: 424

Answers (3)

kander
kander

Reputation: 4306

Simplification of the suggestions proposed by users JohnnyFaldo and som:

$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
   return $row['value'] == true;
});

Upvotes: 0

JohnnyFaldo
JohnnyFaldo

Reputation: 4161

You can decode it as an object or an array, in this example I use an array.

First you want to take the JSON encoded information and decode it into a PHP array, you can use json_decode() for this:

 $data = json_decode($thejson,true); 

 //the Boolean argument is to have the function return an array rather than an object

Then you can loop through it as you would a normal array, and build a new array containing only elements where 'value' matches your needs:

 foreach($data as $item) {

    if($item['value'] == true) {
        $result[] = $item;
    }     

 }

You then have the array

 $result 

at your disposal.

Upvotes: 1

som
som

Reputation: 4656

$arr = array();
$i = 0;
foreach($json as $key => $items) {
    if($items->value == true) {
       $arr[$i]['label'] = $items->label;
       $arr[$i]['name'] = $items->name;
       $i++;
    }
}

Upvotes: 5

Related Questions