首页 > 解决方案 > PHP - 为什么我从我的编码对象数组中得到奇怪的结果?

问题描述

我在 PHP 中有一个对象数组,如何将其作为 JSON 回显?我尝试了 json_encode 但我得到了非常奇怪的结果。JSON 不在 {} 之间,而是在 [] 之间,它在输出的末尾添加了一个 0。我究竟做错了什么?它使我在控制台中的 JSON 错误中得到 Unexpected number。

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

[
    {"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

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');

标签: javascriptphpjson

解决方案


正如评论部分所建议的那样,0 的最佳解决方案可能是在后面放置一个die()json_encode()以防止页面中的其他输出。这也是[]因为值在数组中,而不是在对象中


推荐阅读