Skip to content
Advertisement

place results of each foreach objects into their own columns

I have an array of objects that I am getting values for using foreach:

JavaScript

If I ECHO this, I get results like:

JavaScript

The mysql is

JavaScript

Great! Now since they are objects, if I wanted to get a count on each variation of the type and display that in a table how would I do that?

I have tried adding things like SELECT COUNT(Type), type FROM mytablename or the like and then using my FOREACH loop but that is invalid.

I know how to build a table in PHP with ECHO '<table>' .... '</table>' but don’t know what I am using for the variable in the TD of each in order to achieve this.

Desired Result:

JavaScript

Advertisement

Answer

We can use several built in array functions to get the result you want. By using array_map, we can get the property Type of each object. We can then use array_count_values to get the frequency of each type.

JavaScript

Finally, the table can be rendered using PHP as follows using both array_keys which will return the unique types. While array_values will return the matching frequencies.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement