【问题标题】:Need to remove numeric keys in php array需要删除php数组中的数字键
【发布时间】:2017-08-29 13:34:09
【问题描述】:

下面是我的php数组,

Array
(
    [0] => Array
        (
            [requests] => 22
        )

    [1] => Array
        (
            [requests] => 44
        )
    [overview_chart_data] => Array
        (
            [response] => ok
        )
)

下面是上面数组的php json编码结果,

{"0":{"requests":22},"1":{"requests":44},"overview_chart_data":{"response":"ok"}},

出于某种原因,我需要得到如下结果,

{{"requests":22},{"requests":44},"overview_chart_data":{"response":"ok"}}

是否有可能达到预期的结果..!感谢任何帮助...

【问题讨论】:

  • ...是否有可能达到预期的结果.. 是的!你为此做了什么?
  • 你永远不会得到这样的带有关联数组的json。

标签: php json


【解决方案1】:

您可以为此使用自定义脚本:

<?php
$a = [
    ['requests' => 22],
    ['requests' => 44],
    'overview_chart_data' => ['response' => 'ok']
];
$output = [];
foreach ($a as $k => $v)
    $output[] = (is_string($k) ? ('"' . $k . '":') : '') . json_encode($v);

echo '{' . implode(',', $output) . '}' . PHP_EOL;

但它不是有效的 JSON 文档。

【讨论】:

    【解决方案2】:

    Here is a good S.O. post 帮助您通过这样做获得这些结果...

    $testArray = array(
        (object)array("name" => "John", "hobby" => "hiking"),
        (object)array("name" => "Jane", "hobby" => "dancing")
    );
    
    echo "Person 1 Name: ".$testArray[0]->name;
    echo "Person 2 Hobby: ".$testArray[1]->hobby;
    

    这将为您提供在没有数字索引的数组中包含对象的理想结果......但是更合适的方法是follow this post。这样,您就可以使用正确的 JSON 解码过程来获得执行这种简单语法$obj = json_decode($data); 的能力。

    【讨论】:

      【解决方案3】:

      尝试使用 $array = array_values($array);这样就可以轻松实现您的目标

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-29
        • 2016-04-17
        • 1970-01-01
        相关资源
        最近更新 更多