【问题标题】:Assigning Keys and Values to Array in PHP在 PHP 中为数组分配键和值
【发布时间】:2014-08-12 10:15:32
【问题描述】:

我有以下将我需要的值分配给 php 中的数组

 $resultsAr[$row['stop_name']][$row['route_long_name']][] = $row['arrival_time'];

但是,当我将其转换为 JSON 时,它没有任何键。

echo json_encode($resultsAr);

例如

{
Stop1: {
Destination1: [
"11:13",
"11:25"
],
Destination2: [
"11:15",
"11:27"
],
Destination3: [
"11:14",
"11:23",
"11:26"
]
},

它们的键实际上是值。如何为数组分配键名?

已编辑:所需的 JSON 输出将是带有值的键:

[Stops => all stops] [destinations => destinations] [times => arrival times]

【问题讨论】:

  • 期望的 JSON 输出是什么?还不清楚
  • json_encode(); 工作得非常好。指定的数组结构由您发送给我们的 JSON 表示。你希望你的输出是什么样的?
  • @ClémentMalet 我已经更新了问题 - 我想在数组中包含键 - 不要使用停止/目的地名称作为键
  • @ZanderRootman 是的,它的编码很好 - 只想包含键名,以便在解码时可以引用它们
  • 解码时尝试json_decode($json, true); 此外,“Stop1”、“Destination1”等。是您的数组“键”。所以你的钥匙在那里。

标签: php arrays json key


【解决方案1】:

你可以试试:

$obj = new stdClass();

$obj->name = "Stop1";
$obj->data = array(
    array("Destination1",array("11:13","11:25")),
    array("Destination2",array("11:13","11:25")),
    array("Destination3",array("11:13","11:25")),
    );

echo json_encode($obj);

附注 只有数字项可以不带引号出现。 json.org

还要解释stdclass - What is stdClass in PHP?

【讨论】:

    【解决方案2】:

    要将数组编码为json时,必须为数组设置键

    例子:

    $i=0;
    foreach ($rows as $row) {
           $resultsAr[$row['stop_name']][$row['route_long_name']][$i] = $row['arrival_time'];
           $i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多