【问题标题】:How to return a JSON string into useable data?如何将 JSON 字符串返回为可用数据?
【发布时间】:2014-04-03 15:26:47
【问题描述】:

我正在使用一个插件对我的产品进行分组,然后使用 JSON stringify 获取产品 ID 并在自定义字段中返回以下内容:[{"id":"435"},{"id":" 527"},{"id":"563"},{"id":"568"}].

我想使用它,但不知道如何使用。我根本不懂Java。我正在使用 Wordpress + WooCommerce。我想通过他们的 ID 获取这些帖子。在循环中,我通过

调用自定义字段
<?php
    while (have_posts()) { the_post(); $count++;

        // post data from "Single_Menu" custom field
        echo do_shortcode(get_post_field("menu_listing", $post->ID ));

    } // End WHILE Loop

这是网页上返回的内容

[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]

这是后端元框中的内容。我想要的是返回与这些 ID 相关的实际帖子。有谁知道我如何做到这一点?

【问题讨论】:

    标签: php json wordpress


    【解决方案1】:

    您可以使用内置的 php 函数 json_decode 将该 json 字符串转换为数组数组或对象数组。

    $json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
    $array = json_decode($json);
    

    您现在有了一个可以使用的对象数组。将这些 id 放入另一个数组中,用作 get_posts 的 arguments 参数的一部分。

    $include = array();
    foreach($array as $a) {
        $include[] = $a->ID;
    }
    
    $args = array('posts_per_page' => -1, 'include' => $include);
    $posts = get_posts($args);
    

    $posts 现在是一个帖子对象数组,您可以随意使用。

    【讨论】:

    • 我也在想同样的事情,但都没有工作。我把你的代码放在我的循环和字符串 "[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568" }]" 是所有返回。我认为这是一个小故障(我的网站没有更新),所以我等了几个小时,我也重新启动了我的机器。我也试过这个:$json = do_shortcode(get_post_field("menu_listing", $post-&gt;ID )); $array = print_r(json_decode($json, true)); $args = array( 'post_type' =&gt; 'product', 'meta_query' =&gt; $include, ); $posts = get_posts( $args ); 仍然只是返回字符串。
    • 我的网站现在可能没有更新。我刚刚尝试删除我的 php 文件中的所有代码,并且该字符串仍然出现在网页上。
    • 我已经玩了几天了,但没有得到我想要的结果。我能做到的最好的事情是页面拉入所有帖子,而不仅仅是 $json 字符串的一部分。
    • 我在stackoverflow.com/questions/22974878/…stackoverflow.com/questions/22974878/… 重新发布了我的问题及其完整代码
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多