I am new to php. I need some quick help with json_decode/php. I need to get values of g91 in an array, how can I do this? I suppose there is some recursion value that we can pass to json_decode...
{
"e": "none",
"f": "test",
"g": [
{
"g1": "text2",
"g9": {
"text3": {
"g91": 0,
"g92": [
"text5"
]
}
}
},
{
"g1": "text1",
"g9": {
"text4": {
"g91": 0,
"g92": [
"text6",
"text7"
]
}
}
}
]
}
Please note that text3 is not fixed..in next record, I have text4..
Thanks!
After decode you will get an PHP array, just go to desired index:
$myJson['g'][0]['g9']['text3']['g91'];
But you can make some recursive loop to find all the results you search in that array.
Take a look in array docs from PHP: http://br2.php.net/manual/en/book.array.php
$json = '{
"e": "none",
"f": "test",
"g": [
{
"g1": "text2",
"g9": {
"text3": {
"g91": 0,
"g92": [
"text5"
]
}
}
},
{
"g1": "text1",
"g9": {
"text4": {
"g91": 0,
"g92": [
"text6",
"text7"
]
}
}
}
]
}';
$result = json_decode($json);
var_dump(array_merge($result->g[0]->g9->text3->g91, $result->g[1]->g9->text3->g91));
Pass TRUE
to json_decode as second parameter
$output = json_decode($input,TRUE);
Than traverse the arrays. It should be something like
$output['g'][0]['g9']['text3']['g91']
Refer to json_decode
I updated the JSON for the testing purpose:
<script type="text/javascript">
var json ={
"e": "none",
"f": "test",
"g": [
{
"g1": "text2",
"g9": {
"text3": {
"g91": 83,
"g92": [
"text5"
]
}
}
},
{
"g1": "text1",
"g9": {
"text4": {
"g91": 12,
"g92": [
"text6",
"text7"
]
}
}
}
]
}
var arr=json["g"];
for(key in arr){
var obj=arr[key]["g9"];
for(tex in obj)
{
alert(obj[tex]["g91"]);
}
}
</script>