Sum of a field which stored as an array and group by the same id in laravel 4

时间:2015-04-23 05:29:14

标签: php laravel-4

I have a field in a table called "images" which is stored as an array,

$new_item_photos = Item::whereIn('id', [10, 15, 10])->get();

       foreach ($new_item_photos as $new_photos) {
            if ($new_photos->id == $new_photos->id) {
                $total_photos += count($new_photos->images);
            } else {
                $total_photos = count($new_photos->images);
            }

            echo $total_photos."<br>";
        }

I get a result like

id photos
10 8
15 9
10 7

now I want to sum all the $total_photos and filter the duplicate id from the loop, ex:

id photos
10 15
15 9

Can anyone please help me on this?

PS: The images are saved in array format in the table

1 个答案:

答案 0 :(得分:0)

You can use the array to store the count of photos for each id. This is modified example that helps you further

$new_photos = Item::whereIn('id', [10, 15, 10])->get();
$total_photos=[];

foreach ($new_photos_dealers as $new_photos_dealer) {
    if ($new_photos->id == $new_photos->id) {
    if(array_key_exists($new_photos->id,$total_photos)) {
            $total_photos[$new_photos->id] += count($new_photos->images);
    } else {
            $total_photos[$new_photos->id] = count($new_photos->images);
    {
        $total_photos[$new_photos->id] += count($new_photos->images);
    } else {
        $total_photos[$new_photos->id] = count($new_photos->images);
    }

    echo print_r($total_photos, true)."<br>";
}