0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.