计算JSON数组中相同值的数量并将其转换为字符串

时间:2019-07-09 09:27:33

标签: laravel

我的JSON看起来像这样:

[
   {"pet_type":"Dog","weight":"26","description":"Akita"},
   {"pet_type":"Dog","weight":"6","description":"Pug"},
   {"pet_type":"Cat","weight":"4","description":"Manx"},
   {"pet_type":"Dog","weight":"12","description":"Beagle"},
   {"pet_type":"Cat","weight":"5","description":"Siberian"}
]

如何将其转换为类似于3 Dogs, 2 Cats的字符串?

我尝试的方法是用array填充pet_type,然后使用array_count_values来计数相同记录的数量,后来我在foreach中遍历该数组和concat这样的字符串:

foreach ($count_animals as $type => $number) {
   $animals .=  $number.' '.str_plural($type, $number).', ';
}

这行得通,但是我的问题是,我可以直接从JSON用更少的代码来执行此操作,而不使用更多的foreach循环吗?

2 个答案:

答案 0 :(得分:2)

如果可行,您可以保留代码。

如果您想要更少的代码,则可以使用以下版本:

$json = '[
   {"pet_type":"Dog","weight":"26","description":"Akita"},
   {"pet_type":"Dog","weight":"6","description":"Pug"},
   {"pet_type":"Cat","weight":"4","description":"Manx"},
   {"pet_type":"Dog","weight":"12","description":"Beagle"},
   {"pet_type":"Cat","weight":"5","description":"Siberian"}
]';


print_r(array_count_values(array_map(function($item) {
   return $item['pet_type'];
}, json_decode($json, true))));

将显示:

Array ( [Dog] => 3 [Cat] => 2 )

答案 1 :(得分:2)

in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();

In your blade
 <h1>{{count($petcount)}} Dog</h1>