这是我的代码:

{"subcategories":[],"subcategoriescount":"0","catname":"Gloves","weight":"","products":[{
                            "product_id":"2584",}]

最佳答案

您的JSON数据无法正常工作,因此我添加了丢失的最后一个大括号,并在“ 2584”之后删除了逗号,然后它起作用了(PHP对JSON语法非常敏感)。从Web服务获取JSON数据后,您将通过以下方式获得“ subcategoriescount”:

<?php

$my_data = '{"subcategories":[],"subcategoriescount":"0","catname":"Gloves","weight":"","products":[{"product_id":"2584"}]}';

$my_object = json_decode( $my_data ); // CONVERT FROM JSON TO OBJECT.

echo "Subcategoriescount value is = " .
     $my_object->{"subcategoriescount"};  // WILL DISPLAY "0".

?>


要测试先前的代码,请创建一个文本文件,使用PHP扩展名给它命名,然后复制粘贴该代码,打开浏览器并运行localhost/anyname.php。为确保其正常工作,请转到JSON字符串,并将“ subcategoriescount”的值替换为“ 0”至“ 5”(或其他任何值),您应该在屏幕上看到以下内容:

Subcategoriescount value is = 5

09-13 09:29