javascript图中使用的PHP数组数据 - codeigniter
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)
我在模型中使用API数据,然后传递给控制器然后进行查看。 在一个特定的实例中,我需要做一个foreach()循环但是在javascript中获取我需要的数据,请看下面我是如何做到的。 p>
我知道这是不好的做法 但想知道实现这一目标的最佳做法是什么,所以我知道前进。 p>
categories:[&lt;?php foreach($ champ_name as $ champ_id =&gt; $ stat_value){
foreach($ stat_value as $ cn =&gt; $ cs){
if($ champ_id!= 0){
echo'“'。$ cn。'”,';
}
}
}?&gt;]
code> pre>
感谢您寻找/帮助。 p>
(PS。以上确实有效但是 我知道这不是正确的方式) p>
div>
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