【问题标题】:PHP: setting a number as key in associative arrayPHP:将数字设置为关联数组中的键
【发布时间】:2012-07-26 22:09:54
【问题描述】:

我正在尝试从数据库中为客户端重新创建 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 而不拆分。然而,关于分贝这似乎并不明智。我希望能够单独访问每个文档。使用

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

显然有效,但不幸的是只有一键......

编辑:澄清* 在php中:有区别

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

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

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

已回复HERE

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    试试

    echo json_encode((object)$jsonobj);
    

    【讨论】:

    • 谢谢你在我的情况下成功了!但是关于如何将数字设置为关联数组的键的任何想法?
    • 嗯...我不明白。看来你就是这么做的。
    • 在 php 中:array("a", "b", "c")array ("1" => "a", "2" => "b", "3" => "c") 之间存在差异。后者,当像这样$array["1"] = "a" 完成时,结果是array("a") 而不是array("1" => "a")
    • 看来不可能。见this question
    【解决方案2】:

    我相信如果你通过 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"
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        为了将数字设置为关联数组中的键,我们可以使用以下代码

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-10
          • 1970-01-01
          • 1970-01-01
          • 2015-04-07
          • 2016-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多