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:

foreach($type as $value){
    $value->Type;
};

If I ECHO this, I get results like:

type1
type2
type3
etc.

The mysql is

$type = $wpdb->get_results($wpdb->prepare("SELECT Type FROM mytablename"));

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:

+++++++++++++++++++++++++++++++++++++++
+ type1 +++ type2 +++ type3 +++ type4 +
+   2   +++  3    +++   1   +++  5    +
+++++++++++++++++++++++++++++++++++++++

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.

<?php

$frequencies = array_count_values(
    array_map(
        function ($v) {
            return $v->Type;
        },
        $type
    )
);

ksort($frequencies,  SORT_NATURAL);

?>

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.

<table>
    <tr>
        <?php foreach (array_keys($frequencies) as $type) : ?>
            <th><?= $type ?></th>
        <?php endforeach; ?>
    </tr>
    <tr>
        <?php foreach (array_values($frequencies) as $frequency) : ?>
            <td><?= $frequency ?></td>
        <?php endforeach; ?>
    </tr>
</table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement