0

我需要在 PHP 变量中获取对象信息"label""name"value=true不是在其中value=false

这个JSON数组是怎么做到的?

如果我做一个 var_dumpJSON我得到这个:

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)
  }
}
4

3 回答 3

5
$arr = array();
$i = 0;
foreach($json as $key => $items) {
    if($items->value == true) {
       $arr[$i]['label'] = $items->label;
       $arr[$i]['name'] = $items->name;
       $i++;
    }
}
于 2013-08-02T10:35:25.527 回答
1

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.

于 2013-08-02T10:39:48.503 回答
0

用户 JohnnyFaldo 和 som 提出的建议的简化:

$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
   return $row['value'] == true;
});
于 2013-08-02T11:13:14.957 回答