PHP:在关联数组中设置一个数字作为键


PHP: setting a number as key in associative array

我正试图从数据库中为客户端重新创建json。不幸的是,json中的一些键是数字,在javascript中可以很好地工作,但因此PHP一直将它们视为数字而不是关联数组。每个键都用于一个文档。让我给你看看:

PHP:

  $jsonobj;
  while ($row = mysql_fetch_assoc($ms)) {
            $key = strval($row["localcardid"]);
            $jsonobj[$key] = json_decode($row["json"]);
    }
    // $jsonobj ist still a numeric array
    echo json_encode($jsonobj);

生成的json应该如下所示:

{
  "0": {
    "terd": "10",
    "id": 0,
    "text": "",
    "pos": 1,
    "type": 0,
    "divs": [
        {},
        {}
    ],
    "front": 1
 }
"1": {
     "terd": "10",
    "id": 0,
    "text": "",
    "pos": 1,
    "type": 0,
    "divs": [
        {},
        {}
    ],
    "front": 1
  }
}

一个显而易见的解决方案是保存整个json而不进行拆分。然而,就db而言,这似乎并不明智。我希望能够分别访问每个文档。使用

 $jsonobj = array ($key => json_decode($row["json"]));

显然有效,但不幸的是,只有一把钥匙。。。

编辑:用于澄清*在php中:之间存在差异

array("a", "b", "c")      

   array ("1" => "a", "2" => "b", "3" => "c").

后者,当这样做时$array["1"]="a"导致数组("a")而不是阵列("1"=>"a"

在此处回答

尝试

echo json_encode((object)$jsonobj);

我相信如果您传递JSON_FORCE_OBJECT选项,它应该像您想要的那样输出具有数字索引的对象:

$obj = json_encode($jsonObj, JSON_FORCE_OBJECT);

示例:

$array = array();
$array[0] = array('test' => 'yes', 'div' => 'first', 'span' => 'no');
$array[1] = array('test' => 'no', 'div' => 'second', 'span' => 'no');
$array[2] = array('test' => 'maybe', 'div' => 'third', 'span' => 'yes');
$obj = json_encode($array, JSON_FORCE_OBJECT);
echo $obj;

输出:

{
    "0": {
        "test": "yes",
        "div": "first",
        "span": "no"
    },
    "1": {
        "test": "no",
        "div": "second",
        "span": "no"
    },
    "2": {
        "test": "maybe",
        "div": "third",
        "span": "yes"
    }
}

只需将这两个保存在数据库的一个条目中:单独的字段值和整个json结构保存在单独的列中。通过这种方式,您可以按单个字段进行搜索,并且仍然可以获得有效的json结构,以便于处理。

为了在关联数组中设置一个数字作为键,我们可以使用以下代码

$arr=array(); //declare array variable
$arr[121]='Item1';//assign Value
$arr[457]='Item2';
.
.
.
print_r($arr);//print value