Array structure:
{"id":31,"site":"dev.2","total":"11"} {"id":42,"sitу":"dev.1","total":"13"} {"id":63,"site":"dev.2","total":"15"} It is required to run in a loop and display:
Website | Amount |
dev.2 | 26 |
dev.1 | 13 |
Array structure:
{"id":31,"site":"dev.2","total":"11"} {"id":42,"sitу":"dev.1","total":"13"} {"id":63,"site":"dev.2","total":"15"} It is required to run in a loop and display:
Website | Amount |
dev.2 | 26 |
dev.1 | 13 |
I suggest this option:
<?php $array = ['{"id":31,"site":"dev.2","total":"11"}', '{"id":42,"site":"dev.1","total":"13"}', '{"id":63,"site":"dev.2","total":"15"}']; $newArray = []; foreach ($array as $elem) { $json = json_decode($elem); if(isset($newArray[$json->site])) { // Если ключ есть, то суммируем с текущим значением $newArray[$json->site] += intval($json->total); } else { // Если ключа нет, то добавляем его $newArray[$json->site] = intval($json->total); } } var_dump($newArray); // Тут массив вида ['dev.2' => 26, 'dev.1' => 13] // Исходный массив $array = [ ["id" => 31,"site" => "dev.2", "total" => "11"], ["id" => 42,"site" => "dev.1", "total" => "13"], ["id" => 63,"site" => "dev.2", "total" => "15"] ]; // Выводим заголовок таблицы echo 'Сайт|Сумма<br>'; // Проходимся по каждому подмассиву исходного массива foreach($array as $elem) { // Выводим нужные данные каждого элемента echo $elem['site'].' '.$elem['total'].'<br>'; } If the data comes from MySQL, then MySQL will be added together.
The request is something like this:
SELECT `site` , COUNT( `site` ) AS `count_site` FROM `table` GROUP BY `site` LIMIT 0 , 30 site sum ( total ) AS sum FROM table GROUP BY site - splash58Source: https://ru.stackoverflow.com/questions/778249/
All Articles