【问题标题】:How to create JSON object in php without key name?如何在没有键名的情况下在 php 中创建 JSON 对象?
【发布时间】:2020-09-17 15:47:39
【问题描述】:

我正在尝试在 php 中创建 JSON 对象和数组。但它会创建不需要的索引(键)。有什么方法可以创建没有键名的对象,例如 $temp_obj-> No Key here $all_products_array; ???提前致谢

这就是我的尝试...

$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;

$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
    $all_products_array = array();
    $all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
    $temp_obj->all_products_array_inside[$i] = $all_products_array;
}

$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';

它将产生以下结果,其中名为“1”和“all_products_array_inside”的索引/键是不需要的。因为我必须去 myfinalobl->all_products_array->all_products_array_inside[1].product_id 但我想像 myfinalobl->all_products_array[i].product_id

有什么方法可以创建没有键名的对象 $temp_obj-> 这里没有密钥 $all_products_array; ????

{
    "myfinalobj": {
        "1": {
            "combo_info": {
                "combo_id": "1",
                "combo_name": "Supper_deal",
            },
            "all_products_array": {
                "all_products_array_inside": {
                    "1": {
                        "product_id": "1",
                        "product_name": "TV"
                    },
                    "2": {
                        "product_id": "2",
                        "product_name": "Laptop"
                    }
                }
            }
        }
    }
}

【问题讨论】:

    标签: php arrays json object indexing


    【解决方案1】:

    您正在自己创建密钥(来自$i),所以不要那样做......

    $myfinalobj->myfinalobj[$i] = $myObj;
    

    这里有 [$i] - 删除它:

    $myfinalobj->myfinalobj = $myObj;
    

    【讨论】:

    • 我根本不需要某些对象的索引,所以它应该是什么样子? $temp_obj-> $all_products_array;
    • 虽然没有第二个 $,否则你会说使用 $all_products_array 变量的 contents 作为键名。
    • 假设$test = 'abc'; $obj = new stdClass();。写完$obj-&gt;test = 123'; 后,$objtest 属性将设置为123。写完$obj-&gt;$test = 123;(注意第二个$!)后,$objabc 属性将设置为 123,因为您没有指定名为 @ 的键987654337@ 而是一个以变量$test内容 命名的键,即abc。因此,您可能不想要第二个$
    • 如果我根本不想要键名怎么办?只有价值?有可能吗?
    • 这不合逻辑。你会用什么名字访问它?
    猜你喜欢
    • 1970-01-01
    • 2014-10-02
    • 2012-08-31
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多