我的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
循环吗?
答案 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>