PHP计算多维数组中数组项的出现次数

时间:2015-09-28 20:05:02

标签: php arrays

不再需要这篇文章了。

2 个答案:

答案 0 :(得分:0)

您可以创建一个数组来保存您的计数。使用状态作为键并递增值。

product_id image_url

    22           none.jpg
    22           abcd.jpg
    22           cdfg.jpg

答案 1 :(得分:0)

试试这个:

<?php

$response = array(
    (object) array(
        'status' => 'SHIPPED',
        'country' => 'UNITED STATES'
    ),
    (object) array(
        'status' => 'FAILED',
        'country' => 'UNITED STATES'
    ),
    (object) array(
        'status' => 'SHIPPED',
        'country' => 'UNITED STATES'
    ),
    (object) array(
        'status' => 'COMPLETED',
        'country' => 'UNITED STATES'
    ),
    (object) array(
        'status' => 'SHIPPED',
        'country' => 'UNITED STATES'
    ),
    (object) array(
        'status' => 'FAILED',
        'country' => 'UNITED STATES'
    )
);

$results = array();
foreach ($response as $data) {
    // +1 to each of the status count here
    $results[$data->status] = isset($results[$data->status]) ? $results[$data->status]+1 : $results[$data->status] = 1;
}

echo '<pre>';
echo '$results: ' . print_r($results, true);
echo '</pre>';