2011-08-08 4 views
9

にJSON配列を検索するために私が持っているJSON配列私は8097を検索し、コンテンツを取得する方法をどのようにPHP

{ 
    "people":[ 
    { 
     "id": "8080", 
     "content": "foo" 
    }, 
    { 
     "id": "8097", 
     "content": "bar" 
    } 
    ] 
} 

+0

がどのように多くのpeope-> ID配列 – Ibu

+1

を通過するループを作成することができますので、ここでは(IDの順に限り、人々がそうであるように)正しいものを見つける前に、はるかに少ない人々を検討する別の方法があります人々は代表されていますか?それが十分に小さい場合、以下に提示される探索ループの1つがうまくいく可能性がある。非常に大きい場合は、別のものが必要な場合があります。 –

+0

また、エントリは常にIDの昇順になっていますか?そうであれば、それを基に構築されたアルゴリズムは、すべてのエントリをループするよりもはるかに効率的なものを作り出すことができます。 –

答えて

17

ようjson_decode機能を扱うには、あなたを助ける必要があります。

$str = '{ 
    "people":[ 
    { 
     "id": "8080", 
     "content": "foo" 
    }, 
    { 
     "id": "8097", 
     "content": "bar" 
    } 
    ] 
}'; 

$json = json_decode($str); 
foreach($json->people as $item) 
{ 
    if($item->id == "8097") 
    { 
     echo $item->content; 
    } 
} 
15

json_decode()ことと、他の配列やstdClassのオブジェクト

$arr = json_decode('{ 
    "people":[ 
    { 
     "id": "8080", 
     "content": "foo" 
    }, 
    { 
     "id": "8097", 
     "content": "bar" 
    } 
    ] 
}',true); 

$results = array_filter($arr['people'], function($people) { 
    return $people['id'] == 8097; 
}); 


var_dump($results); 

/* 
array(1) { 
    [1]=> 
    array(2) { 
    ["id"]=> 
    string(4) "8097" 
    ["content"]=> 
    string(3) "bar" 
    } 
} 
*/ 
+1

[array_map](http://php.net/manual/en/function.array-map.php)の引数が順不同だと思います。 –

+0

私はarray_filterの代わりにarray_mapを使用しました。今修正されました。 – Mchl

4

あなたは「人」オブジェクトのかなり数が少ない場合は、以前の答えがあなたのために働くでしょう。あなたの例が8000の範囲のIDを持っているとすれば、私はすべての単一のIDが理想的ではないかもしれないと考えています。

//start with JSON stored as a string in $jsonStr variable 
// pull sorted array from JSON 
$sortedArray = json_decode($jsonStr, true); 
$target = 8097; //this can be changed to any other ID you need to find 
$targetPerson = findContentByIndex($sortedArray, $target, 0, count($sortedArray)); 
if ($targetPerson == -1) //no match was found 
    echo "No Match Found"; 


function findContentByIndex($sortedArray, $target, $low, $high) { 
    //this is basically a binary search 

    if ($high < low) return -1; //match not found 
    $mid = $low + (($high-$low)/2) 
    if ($sortedArray[$mid]['id'] > $target) 
     //search the first half of the remaining objects 
     return findContentByIndex($sortedArray, $target, $low, $mid - 1); 
    else if ($sortedArray[$mid]['id'] < $target) 
     //search the second half of the remaining objects 
     return findContentByIndex($sortedArray, $target, $mid + 1, $high); 
    else 
     //match found! return it! 
     return $sortedArray[$mid]; 
}