2011-08-08 60 views
9

我有一個JSON陣列如何通過JSON陣列搜索在PHP

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

如何將搜索8097和獲取內容?

+0

可以創建一個循環通過peope-> ID陣列 – Ibu

+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_map而不是array_filter。現在修復。 – Mchl

4

如果你有一個相當小的數字「人」的對象,那麼以前的答案將適用於你。鑑於你的例子有8000個範圍的ID,我懷疑看每一個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]; 
}