【问题标题】:PHP storing array as a dictionary, how to get the key and the value? [duplicate]PHP将数组存储为字典,如何获取键和值? [复制]
【发布时间】:2015-09-15 19:37:35
【问题描述】:

这似乎很简单,但我的谷歌搜索似乎无法得到正确答案:

我正在动态地制作一个数组

$data = array();

$data['this is text'] = 1312;
$data['heres more text'] = 191;
$data['im also a unique entry'] = 239

然后我想遍历每个项目并获取键和值:

foreach($data as $datapoint)
{   
    var_dump($datapoint); //this seems to just be the value
    $k = key($garavg); //this does not work because datapoint is a value not an array
}

我只是希望能够做到这一点:

echo "$key has this many entries $value";

【问题讨论】:

  • 查看手册:php.net/manual/en/control-structures.foreach.php(提示:这是foreach ($data as $key => $value))。
  • 您需要学习如何更好地使用 Google。这纯粹是基础知识。
  • 如果它有助于将来的谷歌搜索,“字典”通常在 php 中称为 关联数组
  • 实际上,key 是您问题中的错字,因为它被视为常量(甚至是函数),而不是预期的 $key 变量。另外,从句法上讲;你在这里缺少一个分号$data['im also a unique entry'] = 239只是说,除非它只是一个糟糕的粘贴。

标签: php arrays


【解决方案1】:

foreach 内置:

foreach($data as $key => $value )
{   
    echo "$key has this many entries $value";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多