Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [php] sumowanie tablic
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---


Otrzymuje cos takiego, chce to "zsumowac" (pole "cnt"), aby liczylo sie prawidlowo, czyli dodawalo;

jest to wynik dzialania kodu
$pm = array_merge($pm1,$pm2);

Cytat
array (
0 =>
array (
'id' => '3',
'id_' => '21',
'_from' => '42',
'_from_t' => '',
'_to' => '1',
't' => 'Fabulous',
'date' => '2011-02-27 22:47:54',
'msg' => 'nnnn',
'read' => '1',
'cnt' => '1',
),
1 =>
array (
'id' => '1',
'id_' => '20',
'_from' => '42',
'_from_t' => '',
'_to' => '1',
't' => 'Convenience',
'date' => '2011-02-27 22:46:04',
'msg' => 'dd',
'read' => '1',
'cnt' => '2',
),
2 =>
array (
'id' => '4',
'id_' => '21',
'_from' => '42',
'_from_t' => '',
'_to' => '1',
't' => 'Fabulous',
'date' => '2011-02-27 22:48:24',
'msg' => 'no czesc co tam',
'read' => '1',
'cnt' => '2',
'_temp' => '42',
),
)



NATOMIAST chce uzyskac taki wynik:

  1. 0 =>
  2. 'id' => '3',
  3. 'id_' => '21',
  4. '_from' => '42',
  5. '_from_t' => '',
  6. '_to' => '1',
  7. 't' => 'Fabulous',
  8. 'date' => '2011-02-27 22:47:54',
  9. 'msg' => 'nnnn',
  10. 'read' => '1',
  11. 'cnt' => '3',
  12. ),
  13. 1 =>
  14. 'id' => '1',
  15. 'id_' => '20',
  16. '_from' => '42',
  17. '_from_t' => '',
  18. '_to' => '1',
  19. 't' => 'Convenience',
  20. 'date' => '2011-02-27 22:46:04',
  21. 'msg' => 'dd',
  22. 'read' => '1',
  23. 'cnt' => '2',
  24. ),


jak to zrobic?

  1. $pm = array_merge($pm1,$pm2);
  2. /*
  3. if(!empty($pm1)) {
  4. $pm_ = array_merge($pm1,$pm2); if(!empty($pm_)) {
  5. foreach($pm_ as $v) {
  6. if(!isset($pm[$v['t']])) {
  7. $pm[$v['t']] = $v;
  8. $pm[$v['t']]['cnt']++;
  9. echo $pm[$v['t']]['cnt'].'<br/>';
  10. }
  11. }
  12. } $pm = array_values($pm);
  13. }*/
  14. echo '<pre>';var_export($pm);


zrobilem.

  1. if(!empty($pm1)) {
  2. $pm_ = array_merge($pm1,$pm2); if(!empty($pm_)) {
  3. foreach($pm_ as $v) if(!isset($pm[$v['t']])) $pm[$v['t']] = $v; else $pm[$v['t']]['cnt'] += $v['cnt'];
  4. } $pm = array_values($pm);
  5. }
  6. echo '<pre>';var_export($pm);
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi (1 - 1)
-krzotr-
post
Post #2





Goście







  1. <?php
  2.  
  3. // umieść tutaj tablicę $pm
  4.  
  5. $suma = 0;
  6.  
  7. function sumuj( $val, $key, $suma )
  8. {
  9. if( $key === 'cnt' )
  10. {
  11. $suma += (int) $val;
  12. }
  13. }
  14.  
  15. array_walk_recursive( $pm, 'sumuj', & $suma);
  16.  
  17. echo $suma;
Go to the top of the page
+Quote Post

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

 



RSS Aktualny czas: 21.08.2025 - 20:05