【问题标题】:How to get the first key of many duplicated json key? [duplicate]如何获得许多重复的json键的第一个键? [复制]
【发布时间】:2017-12-28 06:51:21
【问题描述】:

例如`

    $json =
    Array
    (
    [1] => b
    [1] => c
    [1] => d
    ) 

我只想拿第一个 [1] => b 而忽略其余的

【问题讨论】:

  • 在json 甚至在array 中不可能有重复的密钥
  • 键总是唯一的。你不能让它重复
  • 您能解释一下为什么需要这样做吗?
  • 无论是在 json 中,还是在数组中,这都是不可能的。谢谢。检查我在说什么:- eval.in/836017

标签: php arrays json


【解决方案1】:

您在此处提供的不是 JSON,您将无法在 PHP 中创建具有重复键的数组。虽然 对于 JSON 中对象的属性上存在重复键是有效的,但不鼓励这样做,因为大多数解析器(包括 json_decode)不会让您访问所有这些。

但是流解析器通常将让您了解其中的每一个。

使用我写的一个例子,pcrov/JsonReader:

use \pcrov\JsonReader\JsonReader;

$json = <<<'JSON'
{
    "foo": "bar",
    "foo": "baz",
    "foo": "quux"
}
JSON;

$reader = new JsonReader();
$reader->json($json);
$reader->read("foo"); // Read to the first property named "foo"
var_dump($reader->value()); // Dump its value
$reader->close(); // Close the reader, ignoring the rest.

输出:

string(3) "bar"

或者,如果您想获得它们中的每一个:

$reader = new JsonReader();
$reader->json($json);
while ($reader->read("foo")) {
    var_dump($reader->value());
}
$reader->close();

输出:

string(3) "bar"
string(3) "baz"
string(4) "quux"

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 1970-01-01
    • 2014-12-19
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多