English 中文(简体)
PHP - 为 Mongo 插入创建带有数字键的 Json
原标题:PHP - Creating Json with Numeric Keys for Mongo Insert

目前我试图用钥匙模拟每天的时数, 以便插入Mongo,

for($i=0;$i<23;$i++){
    $returnElement["hours"]["$i"] = array();
    foreach($this->list_of_daily_usage_items as $item){
      /* @var $item DailyUsageItem */
      $returnElement["hours"]["$i"][$item->getLabel()] = $item->getDefaultValue();
    }
  }

有了这个,我创造了类似的东西 类似:

 [hours] => Array
    (
        [0] => Array
            (
                [labelOne] => 0
                [labelTwo] => 0
            )
        ....
        [23] => Array
            (
                [labelOne] => 0
                [labelTwo] => 0
            )

    )

然而当我推到JSON的时候, 它转换成:

"hours": [{
    "labelOne": 0,
    "labelTwo": 0,
}, {
    "labelOne": 0,
    "labelTwo": 0,
}]

通常我都会期待; 然而当我试图制作这些数字键时, 这并不是我想看到的。

有没有办法 实现这个短时间的预算 诸如 数字 来强制它到字符串?

谢谢

最佳回答

您可以添加一个临时元素来强制将 PHP 矩阵转换为 JSON 对象

 array("_" => "removeme",
    0 => array("hello" => 0,
           "hell0" => 2),
    1 => array("hello" => 0,
           "hell0" => 2),
    2 => array("hello" => 0,
           "hell0" => 2));

这将产生

{
    "_": "removeme",
    "0": {
        "hello": 0,
        "hell0": 2
    },
    "1": {
        "hello": 0,
        "hell0": 2
    },
    "2": {
        "hello": 0,
        "hell0": 2
    }
}

如果我们把它与纯正正正拼法结合起来, 我们只是把我们过去PHP 有点邪恶的系统:

$finejson = preg_replace("/"_":".*",/", "", $json);

这给了我们这一点:

{
    "0": {
        "hello": 0,
        "hell0": 2
    },
    "1": {
        "hello": 0,
        "hell0": 2
    },
    "2": {
        "hello": 0,
        "hell0": 2
    }
}
问题回答

暂无回答




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签