【问题标题】:PHP need to count how many instaneces of specific value in arrayPHP需要计算数组中有多少特定值的实例
【发布时间】:2021-02-06 06:02:05
【问题描述】:

我有一个 JSON 文件,其结构如下所示(非常简化):

[
  {
    "customerId": "M12345",
    "houses": [
      {
        "id": "OBJ12345_1731321200",
        "status": {
          "id": "4",
          "name": "Sold"
        }
      ],
     "plots": [
      {
        "id": "OBJ12345_1771637082",
        "status": {
          "id": "4",
          "name": "Sold"
        }
       ],
        "projects": [],
        "farms": [],
        "commercialPropertys": [],
        "condominiums": [],
        "foreignProperties": [],
        "premises": []
   }
]

我已经知道如何计算有多少“房子”或“地块”:

$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);

但是试图弄清楚使用 php 如何计算有多少具有条件状态的对象(id:4)

【问题讨论】:

  • 欢迎来到 StackOverflow!也许我错了,但你试过count($GetEstateList[0]["houses"]["status"]["id"]);count($GetEstateList[0]["plots"]["status"]["id"]); 之类的吗?
  • 感谢您抽出宝贵时间查看此内容,但它不起作用...而且只会计算所有状态实例,而不是 id = 4 的情况,对吧?

标签: php json loops object count


【解决方案1】:

我认为您需要使用循环来计算对象,我会使用 foreach 循环,下面是一个示例:

$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
    if (isset($value['status']) && $value['status']['id'] === "4") {
        $count++;
    }
}

【讨论】:

  • 您的代码卡在缺少的参数 status 上,因为该属性仅包含在 housesplots 部分中,我们也可以认为每个部分都需要另一个循环
  • @xKobalt,修改了答案,所以它不会卡住。我刚刚回答了这个问题,我认为小细节是由操作人员解决的,所以他也了解事情是如何工作的。通过提供所有信息他只需要复制代码即可运行,但如果他稍微调试一下,他还将了解它是如何运行的。对吗?
  • 这是一个性能更高的代码,但它仍然不能正常工作,因为它正在搜索不存在的$GetEstateList[0]["status"]。在 status 之前,OP 需要 housesplots 索引,但其中可以有更多元素。所以还需要两个周期(我认为不止一个周期)——无论如何,提出问题的用户确实应该了解其他代码,但提供有效工作的东西更有效率且易于理解,事实上 StackOverflow 是帮助其他人解决编程问题、调试和文档应该属于 OP 的工作
  • 感谢您抽出宝贵时间查看此内容,但它不起作用...
  • @djsringup,我已经编辑了答案,现在应该可以了。
【解决方案2】:

首先,你需要输入GetEstateList数组,然后你需要为每个类型做一个循环(现在显示的类型是plotshouses),那么你需要另一个循环,因为每种类型都是一个元素数组,并且可以有多个属性。

所以,试试这个代码:

// Counter variable for condition expressed after (status == 4)
$counter = 0;

// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {

    // We only need `houses` and `plots` (increasing algorithm performance)
    if ( $array_attr == "houses" || $array_attr == "plots" ) {
        
        // We're checking all types of estates (all `houses` and all `plots`)
        foreach ( $array_attr as $type => $parameter ) {

            // So, we can get `status` of every estate
            if ( $parameter == "status") {

                // And finally we can get `id` for each estate `status`
                if ( $parameter["id"] == "4" ) {

                    $counter++;
                }
            }
        }
    }
}

注意:如果写入的 JSON 结构与原来的差异太大,上面的代码将无法工作。

【讨论】:

  • 看起来不错但返回 0 如果有更多对象(有些是空的)会不会有问题,用空值更新原始问题
  • 逻辑上没问题,我改进了算法以提高其性能。不管怎样,这给你0很奇怪,你能不能试着用id等于4来执行echo count($GetEstateList[0]["houses"]["status"]["id"]);并检查你是否得到1
  • 回声计数($GetEstateList[0]["houses"]["status"]["id"] === 4); // 返回 1
  • 嗯...现在您可以尝试在id 等于4 的情况下执行echo count($GetEstateList[1]["houses"]["status"]["id"]); 吗?我认为问题出在索引上,但我想确定
  • count($GetEstateList[1]["houses"]["status"]["id"] === "4") // 仍然返回 1
【解决方案3】:

我自己想通了... 也许不是“正确”的方式,但它有效! :) 欢迎对任何改进或修改发表评论...

$StatusCount = 0;
   foreach ($GetEstateList[0] as $GetEstateType) { 
      foreach ($GetEstateType as $GetEstate) { 
         if ($GetEstate["status"]["id"] == "4") {
            $StatusCount++;
         }
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多