fupuchu
fupuchu

Reputation: 307

Selecting array in an array in JSON

How do you select an array within an array in a json file?

I managed to display using intval() but it only displays the first number.

The JSON file looks like this:

{
    "arrayone": [{
        "array": ["15000", "20000", "30000"]
    }, {
        "array": ["20000", "40000", "80000"]
    }]
}

And my PHP code looks like this:

<input value="<?php echo $array["array"] ?>" />

Returns me with Array while

<?php echo intval($array) ?>

Returns me with 1.

However I was able to display the values in each array on a <td> using:

<td>
  <?php
    foreach($arrayone->array as $int){
    echo $int . ",";
  }?>
</td>

Which returns me with 15000, 20000, 30000

Upvotes: 0

Views: 31

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

Using intval on any non-empty array will always return 1.

I realize that this is not pretty, I'm not a PHP expert, however I was messing around with this and was able to output the structure of the array by first decoding the JSON, and then looping through each level. If you are more experienced with PHP, I'm sure there may be a cleaner way to iterate through each of these loops. Nonetheless...

  <?php
  $json = '{
    "arrayone": [{
        "array": ["15000", "20000", "30000"]
    }, {
        "array": ["20000", "40000", "80000"]
    }]
}';

   $a = json_decode($json, true);
   foreach($a as $b) {
       echo "arrayone<br />";
       foreach($b as $c) {
           foreach($c as $d) {
               echo "---array<br />";
               foreach($d as $e) {
                   echo "------".$e."<br/>";
               }
           }
       }
   }

?>

OUTPUT:

arrayone
---array
------15000
------20000
------30000
---array
------20000
------40000
------80000

Upvotes: 1

Related Questions