Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [php] wielowymiarowa tablica, sumowanie tych samych kluczy
AndyPSV
post
Post #1





Grupa: Zarejestrowani
Postów: 393
Pomógł: 5
Dołączył: 6.02.2003
Skąd: The.Luciferian.Doctrine.p
df

Ostrzeżenie: (30%)
XX---


Kod
array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 1 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 2 => array ( 'id' => '2', 't' => 'Automotive', ), )


jak to zsumowac, aby dostac:

Kod
array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', 'cnt' => '2' ), 1 => array ( 'id' => '2', 't' => 'Automotive', 'cnt' => '1' ), )
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
redeemer
post
Post #2





Grupa: Zarejestrowani
Postów: 915
Pomógł: 210
Dołączył: 8.09.2009
Skąd: Tomaszów Lubelski/Wrocław

Ostrzeżenie: (0%)
-----


Jeżeli ta tablica jest "wyciągana" z bazy danych, to można to załatwić już na poziomie zapytania SQL:
  1. SELECT id,t,count(*) AS cnt FROM tabela GROUP BY t;

Jeżeli zaś nie, to taki kod powinien zadziałać:
  1. $array = array ( 0 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 1 => array ( 'id' => '6', 't' => 'Food & Beverage', ), 2 => array ( 'id' => '2', 't' => 'Automotive', ), );
  2.  
  3. $return = array();
  4. $count = array();
  5. foreach( $array as $item ) {
  6. if ( !in_array($item, $return) ) {
  7. $return[] = $item;
  8. $count[ $item['id'] ] = 1;
  9. } else {
  10. $count[ $item['id'] ]++;
  11. }
  12. }
  13.  
  14. foreach( $return as & $item ) {
  15. $item['cnt'] = (int)$count[ $item['id'] ];
  16. }
  17.  
  18. var_dump( $return );
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 15.10.2025 - 06:04