2015-05-18 10 views
5

Ho il seguente array JSON, in questo caso ha solo tre voci, ma potrebbe esserci anche di più.JSON: immissione voce con valore specifico

[ 
    { 
     "id": 45, 
     "text": "apple" 
    }, 
    { 
     "id": 37, 
     "text": "pear" 
    }, 
    { 
     "id": 22, 
     "text": "strawberry" 
    } 
] 

Ora la mia domanda è: come faccio ad avere il text variabile della voce con (per esempio) id essendo 37 in PHP? È possibile farlo facilmente?

quello che so: ho potuto utilizzare un ciclo for per trovare il testo come questo (in PHP):

<?php 
    $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file 
    for ($i = 0; $i < count($fruits); $i++) { 
     // Using this for loop and if condition, I get the text I need 
     if ($fruits[$i]['id'] == 37) echo $fruits[$i]['text']; 
    } 
?> 

Ma io non voglio usare un ciclo for, come la mia matrice JSON ha più di 3 voci e se richiedo molti dati in breve tempo ci vuole molto tempo prima che il ciclo for passi attraverso ogni voce. Quindi c'è un modo più efficace per ottenere lo stesso risultato? Qualcuno può spiegarmi questo in PHP?

+0

Penso che devi usare qualsiasi tipo di loop per ottenere le tue informazioni. Si potrebbe usare 'array_filter()' ma questo fa anche un ciclo interno. – TiMESPLiNTER

+0

La maggior parte delle soluzioni suggerite di seguito utilizzano internamente un ciclo (per), quindi non saranno significativamente più veloci della soluzione suggerita. Nel caso in cui sia necessario cercare i dati 'json' più volte, suggerirei di archiviarli come' chiave' 'valore' con' id' come chiave. Questo è già stato suggerito più volte. – Wilt

+0

Controllate la struttura dati Dejori David?Potresti rendere gli elementi ordinati per id quando crei i dati JSON? se è così, è possibile applicare la ricerca binaria su di esso. – Klaus

risposta

0

se è possibile modificare la struttura JSON allora è possibile.

Se si crea JSON come questo

{ 
    "45":{ 
     "text": "apple" 
    }, 
    "37":{ 
     "text": "pear" 
    }, 
    "22":{ 
     "text": "strawberry" 
    } 
} 

e in php

echo $item['37']['text']; 

Questo aiuterà :)

0

modificare questo codice:

<?php 
    $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file 
    for ($i = 0; $i < count($fruits); $i++) { 
     // Using this for loop and if condition, I get the text I need 
     if ($fruits[$i]['id'] == 37) echo $fruits[$i]['text']; 
    } 
?> 

a

<?php 
    $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file 
    foreach ($fruits as $fruit) { 
     // Using this for loop and if condition, I get the text I need 
     if ($fruits['id'] == 37) { 
     echo $fruits['text']; 
     //rest of your code you like to add 
     } 
    } 
?> 

se si intende utilizzare per il ciclo solo allora usare sottostante Codice:

<?php 
    $fruits = json_decode(file_get_contents("file.json"), true); // First I decode the file 
    for ($i = 0; $i < count($fruits); $i++) { 
     // Using this for loop and if condition, I get the text I need 
     if ($fruits['id'] == 37) { 
     echo $fruits['text']; 
     //rest of your code you like to add 
     } 
    } 
?> 
+0

Aggiungete anche un 'break;' nel blocco 'if'. Per fermare il ciclo se hai trovato quello che vuoi. – TiMESPLiNTER

+0

Stai facendo riferimento a '$ fruits' come oggetto quando è stato decodificato come array. Questo genererà errori. – Darren

+1

@Darren, a cura grazie per la notifica. –

0

Si potrebbe farlo semplicemente con questo :

foreach($fruits as $item) { 
    if($item['id'] == 37) { echo $item['text']; break; } 
} 

Example

1

La soluzione con array_filter():

$yourEntry = current(array_filter($jsonArray, function(\stdClass $entry) { 
    return ($entry->id == 37); 
})); 

See the example

+0

Ottiene il mio voto, amo l'alternativa array_filter! – Darren

0

Sei in controllo della struttura dei dati JSON? In tal caso, potresti passare all'accesso tramite la chiave dell'array, ad es.

{ 
    '37': 'pear', 
    '45': 'apple', 
    '22': 'strawberry' 
} 

$ frutta = json_decode (file_get_contents ("file.json"), true);

echo $ fruits ['37 ']; // Pera

Problemi correlati