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

问题描述 投票: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"}
]

我怎样才能将它转换为一个看起来像

3 Dogs, 2 Cats
的字符串?

我尝试的方法是用

array
填充
pet_type
,然后使用
array_count_values
来计算相同记录的数量,然后我在
foreach
中遍历该数组并连接字符串,如下所示:

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

这可行,但我的问题是,我可以用更少的代码直接从

JSON
做到这一点,而不使用更多的
foreach
循环吗?

php arrays laravel multidimensional-array
2个回答
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
投票
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();

In your blade
 <h1>{{count($petcount)}} Dog</h1>
© www.soinside.com 2019 - 2024. All rights reserved.