0

My JSON looks something like this:

[
   {"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"}
]

How could I convert it to a string which would look like3 Dogs, 2 Cats?

The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:

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

This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?

0

2 Answers 2

2

If it works, you can keep your code.

If you want less code, you can use this version :

$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))));

Gonna display :

Array ( [Dog] => 3 [Cat] => 2 )
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.