漂亮的打印对象导致PHP

时间:2019-06-05 12:50:47

标签: php arrays json

我转储的结果如下:

[
[
    "Account Verification",
    null
],
[
    "Account owner",
    null
],
[
    "Account settings",
    null
],
]

我需要修改代码中的语法,使其看起来像这样:

{
  "Account owner" : "null",
  "Account settings" : "null",
...
}

我需要使用json进行漂亮的打印,以使其看起来与众不同。

我的代码:

$printIt = $this->getExampleRepository()->findAll();

$result = [];

 foreach($printIt as $print){
       $name = $print->getName();
       $value = $print->getValue();

        $result[] = array($name, $value);
    }

    $packIt = json_encode($result, JSON_PRETTY_PRINT);

2 个答案:

答案 0 :(得分:1)

$data = [
    [
        "Account Verification",
        null
    ],
    [
        "Account owner",
        null
    ],
    [
        "Account settings",
        null
    ]
];

$data = array_reduce($data, function($a, $b) {
    $a[$b[0]] = $b[1];
    return $a;
}, []);

echo json_encode($data, JSON_PRETTY_PRINT);

DEMO

答案 1 :(得分:0)

据我所知

$result = [];
foreach ($arr as $key => $value) {
    list($name,$value1) = $value;
    // key value pair making and saving to result
    $result[$name] = (!is_null($value1) ? $value1 : "null");
}
echo json_encode($result, JSON_PRETTY_PRINT);

输出

{
    "Account Verification": "null",
    "Account owner": "null",
    "Account settings": "null"
}

Working demo.