0

I am using API data in a model which is passed through to a controller then to view. In one particular instance I need to do a foreach() loop but in javascript to get the data I need, please see below how I've done it.

I know this is bad practice but wanted to know what the best practice is to achieve this so I know going forward.

categories: [<?php foreach($champ_name as $champ_id => $stat_value) {
               foreach ($stat_value as $cn => $cs) {
                   if($champ_id != 0) {
                       echo '"'.$cn.'",';
                   }
               } 
            } ?>]

Thanks for looking/helping.

(PS. the above does work but I know is not the right way)

1
  • use json_encode() instead of hand-building fragile strings... Commented Jun 20, 2013 at 16:14

1 Answer 1

2

You can use json_encode() to convert it into an object or array that Javascript can use.

categories: <?php echo json_encode($myThing); ?>

For your use, you would still need your foreach logic to build an array to be json encoded.

If you build the array manually like in your question, you need to be mindful over special characters from breaking the array and causing syntax errors. For example if any of your $cn contained a double quote, it would produce a syntax error. The benefit of json encoding it is that any special characters will be taken care of without you having to handle them.

Example:

$arr = array('abc', 3, 'te"xt', 6);
echo json_encode($arr);

Outputs

["abc",3,"te\"xt",6]
            ^ qoute has been automatically escaped
Sign up to request clarification or add additional context in comments.

2 Comments

Cool this is very helpful - I will do this when I get home. So after encoding it into json, would I just do a javascript foreach just like I have done above?
Yes, the JSON is valid javascript syntax so you can echo it directly into Javascript code and work with it as normal (be sure to assign it to a variable).

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.