-1

I am having a slight issue in optimizing my code to output the values in the Json Array stored inside a PHP array.

This is the sample array

Array
(
    [0] => Array
    (
        [0] => ["string 1", "string 2", "string 3"]
    )

    [1] => Array
    (
        [0] => ["string 4", "string 5", "string 6"]
    )
    .....
)

This is the code I am using and it works

  $q = EstateTypes::query()->lists('column_value');

  $array1 = json_decode($q[0], true);
  $array2 = json_decode($q[1], true);
  $array3 = json_decode($q[2], true);

  foreach ($array1 as $key => $value) {
      echo $value . "<br>";
  }
   foreach ($array2 as $key => $value) {
      echo $value . "<br>";
  }
  foreach ($array3 as $key => $value) {
      echo $value . "<br>";
  }

I hope you see that the problem is this code is duplicating itself a lot. I've been trying to solve it properly but have been unable to. Would be glad for any help or further pointers on what I should do.

4
  • Can't you just use foreach for $q? Commented Jul 7, 2016 at 11:35
  • why so many foreach loops? Commented Jul 7, 2016 at 11:35
  • Try it again with one loop over $q Commented Jul 7, 2016 at 11:37
  • If i just use foreach, then it outputs the whole json array, not individual values. And if i put the $value in the json_decode() then it throws an error "array to string conversion" Commented Jul 7, 2016 at 11:37

1 Answer 1

3
$q = EstateTypes::query()->lists('column_value');

foreach($q as $item){
    $array = json_decode($item, true);
    foreach ($array as $value) {
        echo $value . "<br>";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I will accept your answer as soon as I can

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.