使用静态索引将PHP数组更改为JSON数组

时间:2015-07-01 09:05:38

标签: php arrays json

我有以下PHP生成的数组值。

Array
( [1] => Array
        (
            [2] => 12:00
            [3] => 12:30
            [4] => 13:00
            [5] => 13:30
        )
  [2] => Array
        (
            [2] => 12:00
            [3] => 12:30
            [4] => 13:00
            [5] => 13:30
            [6] => 14:00
        )
)

我想将其转换为具有静态索引的JSON数组值。 如果我使用echo json_encode array("Timeslots"=>$arry)我会得到以下结果,

"TimeSlots":{"2":{"2":"12:00","3":"12:30","4":"13:00","5":"13:30"},
         "3":{"2":"12:00","3":"12:30","4":"13:00","5":"13:30","6":"14:00"}}

但是我想显示带有静态索引的json数组,称为slot而不是1,2,3 ,, 我的预期输出应该如下,

{
    "TimeSlots":{"2":[{"slot":"12:00"},{"slot":"12:30"},{"slot":"13:00"},{"slot":"13:30"}]},
                 "3":[{"slot":"12:00"},{"slot":"12:30"},{"slot":"13:00"},{"slot":"13:30"},{"slot":"14:00"}]}
}

我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果你想要那个确切的输出,你的数组的索引不能从2开始,因为这意味着它创建的json字符串也总是包含条目的键,这显然你不想拥有你的json字符串。

如果您的数组从0开始向上计数,则json中不会出现关键字:

$timeslots = array('Timeslots' => array(
    1 => array(
            array('slot'=>'12:00'),
            array('slot'=>'12:30'),
            array('slot'=>'13:00'),
            array('slot'=>'13:30')
         ),
    2 => array(
            array('slot'=>'12:00'),
            array('slot'=>'12:30'),
            array('slot'=>'13:00'),
            array('slot'=>'13:30'),
            array('slot'=>'14:00')
        )
    ),
);

创建以下json:

{"Timeslots":{"1":[{"slot":"12:00"},{"slot":"12:30"},{"slot":"13:00"},{"slot":"13:30"}],"2":[{"slot":"12:00"},{"slot":"12:30"},{"slot":"13:00"},{"slot":"13:30"},{"slot":"14:00"}]}}

如果您想操作原始数组以创建此输出,您可以这样做:

$newArray = array();
foreach($array as $key=>$entry) {
    foreach($entry as $subEntry) {
        $newArray[$key][] = array('slot' => $subEntry);
    }
}
$newArray = array('Timeslots' => $newArray);

然后json_encode($newArray)将获得相同的输出。

答案 1 :(得分:1)

$arry = array( 1 => array(2 => '12:00', 3 => '12:30', 4 => '13:00', 5 => '13:30'), 2 => array( 2 => '12:00', 3 => '12:30', 4 => '13:00', 5 => '13:30', 6 => '14:00'));
foreach($arry as $key => $value) {
    $slots = array_values($value);
    foreach ($slots as $key2 => $slot) {
        $slots[$key2] = array('slot' => $slot );
    }
    $arry[$key] = array_values($slots);
}
echo json_encode(array("Timeslots"=>$arry));

编辑:忘记了“插槽”键,这有效。