2013-08-02 78 views
0

我需要获取"label","name"的对象信息,其中value=true在PHP变量中,而不是value=false从JSON获取PHP的价值

这个JSON数组是如何完成的?

如果我做JSON的的var_dump我得到这个:

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) 
    } 
} 
+0

你的意思是'json_encode()'和'json_decode()'? – hjpotter92

+1

*“这个JSON数组是如何完成的?”*这里没有JSON,看起来像是倾倒出一个PHP对象图的结果。你可以编辑你的问题,让它更清楚你实际处理的是什么数据?并添加你已经尝试过的细节等。 –

+0

我想他是问这是否可以用简单的json_encode([...],函数($ el){return $ el.value})来完成,答案是没有。 –

回答

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++; 
    } 
} 
1

可以作为一个对象或数组,在这个例子中,我使用一个数组进行解码。

首先要采取的JSON编码信息,并将其解码成PHP数组,你可以使用json_decode()此:

$data = json_decode($thejson,true); 

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

然后,你可以通过它循环,你会正常的阵列,并建立仅包含元素的新数组,其中的“价值”满足你的需要:

foreach($data as $item) { 

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

} 

然后,您有数组

$result 

在您的处置。

0

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

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