【问题标题】:PHP Select Unique Values from ArrayPHP 从数组中选择唯一值
【发布时间】:2017-10-10 10:35:49
【问题描述】:

我使用 PHP 和 MySQL 生成了一个数组(通过 API 查找)。数组的var_dump 可以看到here

我想从该数组中返回个唯一的“标题”值。

到目前为止我的代码是;

foreach($response["Items"]["Item"] as $item)
{
    $title = $item["ItemAttributes"]["Title"];
}

var_dump$title 产生;

string(5) "Panic" string(5) "Panic" string(73) "Captain Flinn and the Pirate Dinosaurs: Missing Treasure! (Captain Flinn)"

您可以看到有两个名为“Panic”的字符串值。

我尝试过array_unique,但似乎无法正常工作。

感谢任何帮助。谢谢

【问题讨论】:

  • 使用查询获取记录时为什么不尝试mysql的distinct()函数
  • @mickmackusa 标签已更新

标签: php arrays sorting foreach


【解决方案1】:

试试这个技巧:如果标题已经存在,则不会添加。

$titlesFounded = [];

foreach($response["Items"]["Item"] as $item) {
    if (!in_array($item["ItemAttributes"]["Title"], $titlesFounded)) {
        $titlesFounded[] = $item["ItemAttributes"]["Title"];
    }
}

【讨论】:

  • $titlesFounded[] 中的if 中删除[]
  • 有一个错字。固定。
猜你喜欢
  • 2023-03-30
  • 2020-08-30
  • 1970-01-01
  • 2012-01-24
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多