简体   繁体   English

获取foreach循环PHP中相同值的计数

[英]get the count of the same values in foreach loop PHP

I have an array of repeated values of same column and different values of same column.So i'm trying get the one final array which can contains all the data. 我有一个数组的同一列的重复值和同一列的不同值。所以我试图得到一个可以包含所有数据的最终数组。

Actual array: 实际数组:

array:4 [▼
  0 => {#820 ▼
    +"id": 318
    +"asset_id": 11
    +"job_id": 37
    +"asset_name": "Mini Paver"
    +"shift": "AM
  }
  1 => {#819 ▼
    +"id": 319
    +"asset_id": 39
    +"job_id": 37
    +"asset_name": "Road Sweeper"
    +"shift": "AM
  }
  2 => {#701 ▼
    +"id": 320
    +"asset_id": 11
    +"job_id": 37
    +"asset_name": "Mini Paver"
    +"shift": "AM
  }
  3 => {#825 ▼
    +"id": 321
    +"asset_id": 39
    +"job_id": 37
    +"asset_name": "Road Sweeper"
    +"shift": "AM

  }
]

and by using below for each loop I'm trying to get the one array out of four. 通过在每个循环中使用下面的方法,我试图从四个数组中获取一个。

 $jobArr = array();
  foreach ($job_data as $data) {

            $jobArr[$data['job_id']]['job_id']       = $data->job_id;
            $jobArr[$data['job_id']]['shift']        = $data->shift;
            $jobArr[$data['job_id']]['asset_name'][] = $data->asset_name;

        }

and output for the above foreach is as below 上面的foreach的输出如下

array:1 [▼
  37 => array:8 [▼
    "job_id" => 37
    "shift" => "AM"
    "asset_name" => array:2 [▼
      0 => "Road Sweeper "
      1 => "Mini Paver "
    ]
  ]
]

Actually I need to get the count as well like how many asset names are there with the same name which should look like below 实际上,我需要获取计数以及有多少个具有相同名称的资产名称,如下所示

array:1 [▼
  37 => array:8 [▼
    "job_id" => 37
    "shift" => "AM"
    "asset_name" => array:2 [▼
      0 => "Road Sweeper (2)"
      1 => "Mini Paver (2)"
    ]
  ]
]

How do i get the count of same asset_name and the result array as like same above. 我如何像上面一样获得相同的asset_name和结果数组的计数。 Any suggestions please. 有任何建议请。

After you've built your grouped array as shown, you can iterate it and use array_count_values to generate an array in the new format, then replace the asset_name array with the new array. 如图所示构建分组数组后,可以对其进行迭代并使用array_count_values生成新格式的数组,然后用新数组替换asset_name数组。

foreach ($jobArr as $job_id => $job) {

    // iterate the counted values and build your array with the desired format
    foreach(array_count_values($job['asset_name']) as $asset => $count) {
        $counts[] = "$asset ($count)";
    }

    // replace the old asset_name key with your new counted/formatted array
    $jobArr[$job_id]['asset_name'] = $counts;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM