简体   繁体   English

PHP 多维数组转换为 JSON 对象,不显示索引

[英]PHP multidimensional array into JSON object without indexes showing

I have form output coming from repeater looking like this:我有来自中继器的表单输出,如下所示:

array:2 [ 0 => array:1 ["participant_name" => "John" ], 0 => array:1 ["participant_name" => "Jane" ]]

I need to make from this JSON object looking like this:我需要从这个 JSON 对象看起来像这样:

{{"participant_name":"John"},{"participant_name":"Jane"}}

So far I tried $participantsJson = json_encode( array_values($participants) , JSON_FORCE_OBJECT);到目前为止,我尝试了$participantsJson = json_encode( array_values($participants) , JSON_FORCE_OBJECT); but I'm always getting this shape但我总是得到这个形状

 {"0":{"participant_name":"John"},"1":{"participant_name":"Jane"}}

How to get rid of those indexes?如何摆脱这些索引?

Your attempt is tto complex, use the immediate approach:您的尝试很复杂,请使用直接方法:

<?php
$input = [
  ["participant_name" => "John" ], 
  ["participant_name" => "Jane" ],
];
$output = json_encode($input);
var_dump($output);

The output is:输出是:

string(57) "[{"participant_name":"John"},{"participant_name":"Jane"}]"

Not that the output is an array encoded in JSON format...并不是说输出是以 JSON 格式编码的数组......

Your question demonstrates an encoded object instead, but that is invalid JSON.您的问题展示了一个编码对象,但这是无效的 JSON。 Reason is that properties inside an object need to have a name , that is how objects are defined.原因是对象内部的属性需要有一个name ,这就是对象的定义方式。 You cannot have an object holding members without a name (what you called an "index" in your question).您不能拥有一个没有名称的对象(您在问题中称之为“索引”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM