2
$i=0;
foreach($tagss as $tagdetails)
    {
        if($i==0)
 $tags_array[]["00"]=array("id"=>$i,"name"=>"all","type"=>"gift_finder","parent_id"=>null,"url"=>"all","readonly"=>"0","deleted"=>"0");


 $tags_array[][$tagdetails->id]=array("id"=>$tagdetails->id,"name"=>$tagdetails->title,"type"=>"gift_finder","parent_id"=>null,"url"=>$tagdetails->title,"readonly"=>"0","deleted"=>"0");


    $i++;
    }
echo json_encode($tags_array);

我上面的代码输出是:-

[{"00":{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0","deleted":"0"}},{"1":{"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},{"2":{"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}}] 

这是正确的,但我想要输出(只需要 0 而不是 00)所以我尝试了:-

   $i=0;
foreach($tagss as $tagdetails)
    {
        if($i==0)
 $tags_array[]["0"]=array("id"=>$i,"name"=>"all","type"=>"gift_finder","parent_id"=>null,"url"=>"all","readonly"=>"0","deleted"=>"0");


 $tags_array[][$tagdetails->id]=array("id"=>$tagdetails->id,"name"=>$tagdetails->title,"type"=>"gift_finder","parent_id"=>null,"url"=>$tagdetails->title,"readonly"=>"0","deleted"=>"0");


    $i++;
    }
echo json_encode($tags_array);

上述代码的输出:-

[[{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0","deleted":"0"}],{"1":{"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},{"2":{"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}}] 

这在逻辑上是正确的,它将第一个元素放入数组中并在第一个索引处处理下一个元素,但我需要单独的 0 索引

任何建议请提前感谢。

总之我需要

[{"0":{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0",
"deleted":"0"}},
{"1":"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},
{"2":"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}
}] 
4

1 回答 1

2

您只需要将选项传递给您的json_encode()电话。它是JSON_FORCE_OBJECT

echo json_encode($tags_array, JSON_FORCE_OBJECT);

然后你就可以生成一个数字键的对象(所以你根本不需要从 PHP 传递键)。请注意,自 PHP 5.3 起可用

于 2013-09-06T14:05:41.727 回答