2013-08-02 5 views
0

"label", "name"에 대한 객체 정보를 얻으려면 이 아닌 PHP 변수에 value=true이 필요합니다.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 ([...], function ($ 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

당신은 내가 배열을 사용하여이 예에서 객체 나 배열로 디코딩 할 수있다.

$data = json_decode($thejson,true); 

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

그럼 할 수 있습니다 당신과 같은 그것을 통해 루프 것 정상적인 배열 및 구축 :

먼저 당신은 당신이 이것에 대한 json_decode()을 사용할 수 있으며, JSON을 인코딩 정보를 가지고 가고 PHP 배열로 디코딩 할

foreach($data as $item) { 

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

} 

그런 다음 배열

$result 
이 있습니다 만 요소를 포함하는 새로운 배열을 '값은'당신의 요구를 일치합니다

을 처분하십시오. 사용자 JohnnyFaldo에 의해 제안 된 제안과 솜의

0

단순화 :

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