[英]PHP - Why am I getting wierd result from my encoded object array?
I have an object array in PHP, how can I echo this as JSON?我在 PHP 中有一个 object 阵列,我怎样才能将其呼应为 JSON? I tried the json_encode but I am getting very strange results.
我尝试了 json_encode 但我得到了非常奇怪的结果。 The JSON is not between {} but between [] and it adds a 0 at the end of the output.
JSON 不在 {} 之间,而是在 [] 之间,它在 output 的末尾添加了一个 0。 What am I doing wrong?
我究竟做错了什么? It makes me get an Unexpected number in JSON error in the console.
它让我在控制台中的 JSON 错误中得到 Unexpected number。
PHP PHP
function do_get_children_as_hierarchy()
{
if (!isset($_GET) || !isset($_GET['taxonomy_name'])) {
echo "Parameter is missing.";
die;
}
$taxonomy = $_GET['taxonomy_name'];
$terms = get_terms(array(
'taxonomy' => $taxonomy,
));
$termObjects = [];
foreach ($terms as $term) {
$depth = count(get_ancestors($term->term_id, $taxonomy));
$obj = (object) array('term_id' => $term->term_id, 'name' => $term->name, 'depth' => $depth);
array_push($termObjects, $obj);
}
echo json_encode($termObjects);
}
add_action('wp_ajax_get_children_as_hierarchy', 'do_get_children_as_hierarchy');
add_action('wp_ajax_nopriv_get_children_as_hierarchy', 'do_get_children_as_hierarchy');
JSON JSON
[
{"term_id":415,"name":"1 kanaals","depth":2},
{"term_id":416,"name":"12 kanaals","depth":2},
{"term_id":417,"name":"24 kanaals","depth":2}
]0
Javascript Javascript
function do_get_terms_as_hierarchy()
{
return '<script>
var data = {
"action":"get_children_as_hierarchy",
"taxonomy_name":"productcategorie",
};
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "GET",
data: data,
}).then(response => {
console.log(JSON.parse(response));
});
</script>';
}
add_shortcode('get_terms_as_hierarchy','do_get_terms_as_hierarchy');
As suggested in the comment section, probably the best solution for the 0 is to put a die()
after json_encode()
in order to prevent other output in the page.正如评论部分所建议的那样,0 的最佳解决方案可能是在
json_encode()
die()
以防止页面中出现其他 output 。 Also the []
it's because the values are inside an array, not an object还有
[]
这是因为值在数组中,而不是 object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.