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 |

  • do you have json? or did you just portray the PHP array? - splash58
  • array comes from MySql - Domilola

3 answers 3

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] 
  • The question is, when I want to identify an element, an error pops up. How do I get to load more elements to end up with an array in the array. In general, $ newArray [$ json-> site] ['total'] = intval ($ json-> total); does not work. - Domilola
 // Исходный массив $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 
    • SELECT site sum ( total ) AS sum FROM table GROUP BY site - splash58