【问题标题】:php foreach loop giving only 1 result from the arrayphp foreach 循环仅给出数组中的 1 个结果
【发布时间】:2021-05-24 03:49:25
【问题描述】:

我有一个csv file,其中包含要在项目中显示的商店属性(id、名称、类别、特色等)。现在,我需要显示条件为 'featured'='TRUE' 的特色商店数组。有10 results

这是读取文件并将数据保存为关联数组的代码

  function read_all_stores() {
  $file_name = 'csv_files/stores.csv';
  $fp = fopen($file_name, 'r');
  $first = fgetcsv($fp); // get the first row aka headlines of the file
  $stores = [];
  while ($row = fgetcsv($fp)) {
    $i = 0;
    $store = [];
    foreach ($first as $col_name) {
      $store[$col_name] =  $row[$i];
      $i++;
    }
    $stores[] = $store;
  }
  return $stores;
}

sample result of the first 5 stores

现在我只想显示具有属性 features = 'TRUE' 的商店。我试过这段代码:

function get_store() {
    $stores = read_all_stores();
    $feature = [];
    foreach ($stores as $s) {
      while ($s['featured'] == 'TRUE') {
        $feature[] = $s;
        return $feature;
      }
    }
    return false;
  }

但它只返回one result

我尝试删除单引号,但它似乎只接受 'TRUE' 值作为字符串而不是布尔值。如何修复这个 foreach 循环??

【问题讨论】:

  • 是这条线导致了问题吗? $stores[] = $store;。此外,在get_store 方法中,一旦有匹配项,您就会返回。我认为您应该将所有匹配的添加到一个数组中,然后在方法的末尾返回。

标签: php arrays csv foreach


【解决方案1】:

您的问题是,一旦找到匹配结果:$s['featured'] == 'TRUE',您就返回它:return $feature;。相反,您需要在返回结果之前处理$stores 中的所有 值。如果有匹配的商店(count($feature) 不为零,即 truthy),则返回它们,否则返回 false。

function get_store() {
    $stores = read_all_stores();
    $feature = [];
    foreach ($stores as $s) {
        if ($s['featured'] == 'TRUE') {
            $feature[] = $s;
        }
    }
    return count($feature) ? $feature : false;
}

【讨论】:

  • 这与之前添加的评论有何不同?
  • @fiveelements cmets 不是答案。您可以选择添加答案,但选择发表评论,但实际上并没有提供太多细节。我给 OP 回答了他们的问题。
  • @treepl 不用担心 - 我很高兴能帮上忙。
【解决方案2】:

您的代码中有两个问题:

  1. get_store() 方法中,您将在找到匹配项后立即返回。相反,您应该添加所有匹配的,然后在最后返回。
  2. 为了检查匹配你应该使用if而不是while

这是您的代码的修改版本:

<?php
function read_all_stores() {
    $file_name = 'stores.csv';
    $fp = fopen($file_name, 'r');
    $first = fgetcsv($fp); // get the first row aka headlines of the file
    $stores = [];
    while ($row = fgetcsv($fp)) {
        $i = 0;
        $store = [];
        foreach ($first as $col_name) {
        $store[$col_name] =  $row[$i];
        $i++;
        }
        $stores[] = $store;
    }
    return $stores;
}
function get_store() {
    $stores = read_all_stores();
    $feature = [];
    foreach ($stores as $s) {
        if ($s['featured'] == 'TRUE') {
        $feature[] = $s;
        }
    }
    return $feature;
}

echo count(get_store());

【讨论】:

  • 谢谢它现在可以工作了!!还有在什么情况下我应该使用while和if?
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 2019-01-07
  • 2015-10-10
  • 2014-01-08
  • 1970-01-01
相关资源
最近更新 更多