0

在你回答之前,我知道 0 返回 null、false 或空字符串,这就是问题所在。我想知道是否有解决方法。

我试图将 php 数组转换为 json,但 json_encode() 函数没有保留索引,我的数组是。

    Array
    (
      [0] => Array
      (
        [0] => Array
          (
            [idCategory] => 1
            [name] => Carteiras
            [parent] => 0
            [weight] => 0
          )
        [1] => Array
          (
            [idCategory] => 2
            [name] => Bolsas
            [parent] => 0
            [weight] => 1
          )
        [2] => Array
          (
            [idCategory] => 3
            [name] => Cintos
            [parent] => 0
            [weight] => 2
          )
        [3] => Array
          (
            [idCategory] => 4
            [name] => Chinelos
            [parent] => 0
            [weight] => 3
          )
        [4] => Array
          (
            [idCategory] => 5
            [name] => Tênis Masculino
            [parent] => 0
            [weight] => 4
          )
        [5] => Array
          (
            [idCategory] => 6
            [name] => Rasteiras
            [parent] => 1
            [weight] => 5
          )
       )
    )

json:

{"Menu": [
  [
    {
      "idCategory": "1",
      "name": "Carteiras",
      "parent": "0",
      "weight": "0"
    },
    {
      "idCategory": "2",
      "name": "Bolsas",
      "parent": "0",
      "weight": "1"
    },
    {
      "idCategory": "3",
      "name": "Cintos",
      "parent": "0",
      "weight": "2"
    },
    {
      "idCategory": "4",
      "name": "Chinelos",
      "parent": "0",
      "weight": "3"
    },
    {
      "idCategory": "5",
      "name": null,
      "parent": "0",
      "weight": "4"
    },
    {
      "idCategory": "6",
      "name": "Rasteiras",
      "parent": "1",
      "weight": "5"
    }
  ]
]}

我设置的第一个数组

    $i = 0;
    $array[$i] = $somearray;

包含 idCategory、name、parent 和 weight 的数组我使用

    $somearray[] = $node;

如果我使用一切正常

    $array[$i . '_id'] = $somearray;
4

1 回答 1

0

JSON 只接受字符串作为键。最简单的解决方法是用单引号封装索引,这将产生与 $i.'_id' 相同的效果。

   Array
(
  ['0'] => Array
  (
    ['0'] => Array
      (
        [idCategory] => 1
        [name] => Carteiras
        [parent] => 0
        [weight] => 0
      )
  )
)

如果您想转换一个变量,您可以使用双引号,"$1"或者您可以使用该strval()函数将您的整数转换为字符串。

另请参阅:使用数字作为“索引”(JSON) 和:在 PHP 中将整数转换为字符串

于 2013-10-29T16:29:03.133 回答