2011-08-08 18 views
9

Tengo una matriz JSONCómo buscar a través de una matriz JSON en PHP

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

Cómo me gustaría buscar para 8097 y obtener el contenido?

+0

puede crear un bucle para pasar por peope-> array Identificación – Ibu

+1

¿Cuántas las personas están representadas? Si es suficientemente pequeño, entonces uno de los bucles de búsqueda presentados a continuación podría funcionar bien. Si es muy grande, es posible que necesite algo más. –

+0

Además, ¿las entradas están siempre en orden creciente de id? Si es así, un algoritmo construido alrededor de eso podría producir algo mucho más eficiente que recorrer cada entrada. –

Respuesta

17

La función json_decode pueden serle de ayuda:

$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() y tratarlo como cualquier otra matriz o un objeto 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

Creo que tiene los argumentos para [matriz_Mapa] (http://php.net/manual/en/function.array-map.php) fuera de servicio. –

+0

Utilicé array_map en lugar de array_filter. Corregido ahora. – Mchl

4

Si usted tiene un número bastante reducido de objetos "pueblo", entonces las respuestas anteriores funcionarán para ti. Dado que su ejemplo tiene identificaciones en el rango de 8000, sospecho que mirar todas las identificaciones podría no ser ideal. Así que aquí es otro método que va a examinar un número mucho menor de personas antes de encontrar la correcta (siempre y cuando las personas están en el orden de Identificación):

//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]; 
} 
Cuestiones relacionadas