[英]Use json_encode() with a foreach loop
I have the following code which allows me to echo my product categories in wordpress withing a select box: 我有以下代码,可让我使用选择框在wordpress中回显我的产品类别:
$arguments = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_cats = get_terms( 'product_cat', $arguments );
foreach ( $product_cats as $cat ) :
echo '<option value="' . $cat->term_id . '">' . $cat->name . '</option>';
endforeach;
I am trying to use the returned values from my foreach loop within the json_encode() so that I can use the categories in my javascript code. 我试图在json_encode()中使用我的foreach循环返回的值,以便可以在JavaScript代码中使用类别。
But I cannot figure out a way to do it, can anyone provide any guidance? 但是我想不通一种方法,有人可以提供任何指导吗?
If i use 如果我用
<?php echo json_encode($product_cats); ?>
it does not work 这是行不通的
try in javascript tag; 尝试使用javascript标签;
<script type="text/javascript">
var myCatJSON = JSON.parse('<?php echo json_encode($product_cats); ?>');
</script>
You can do this inside a javascript tag. 您可以在javascript标记内执行此操作。 Remember the code should be outside PHP tag.
请记住,代码应在PHP标记之外。
<script type='text/javascript'>
<?php
$cat_array = json_encode($product_cats);
echo "var javasc_cat_array = ". $cat_array . ";\n";
?>
</script>
As other answers suggested try to put it in the script tags like this: 正如其他答案建议的那样,请尝试将其放入脚本标签中,如下所示:
<script>
var cat = <?=json_encode($product_cats); ?>
</script>
And then you can use cat as a javascript object. 然后,您可以将cat用作javascript对象。
PS : Don't forget to use this BEFORE you do the foreach loop as it "empties" the array. PS: 在执行foreach循环之前,请不要忘记使用此功能,因为它会“清空”阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.