Endeks 2D Array birikir

2 Cevap php

Şöyle bir dizi var:

Array
(
    [0] => Array
        (
            [amount] => 60.00
            [store_id] => 1
        )

    [1] => Array
        (
            [amount] => 40.00
            [store_id] => 1
        )

    [2] => Array
        (
            [amount] => 10.00
            [store_id] => 2
        )
)

Ne bir store_id ilgili 'miktarını' toplamları benzer bir dizi dizi azaltmak için iyi bir yöntem olacaktır.

Örneğin ben bu almak istiyorum:

Array
(
    [0] => Array
        (
            [amount] => 100.00
            [store_id] => 1
        )


    [2] => Array
        (
            [amount] => 10.00
            [store_id] => 2
        )
)

2 Cevap

Sizin için sordunuz tam olarak ne çoğaltmak için:

<?php

$stores = array();
$result = array();
foreach($rows as $i => $entry) {
  if (false === ($j = array_search($entry['store'], $stores))) {
    $stores[$i] = $entry['store'];
    $result[$i] = $entry;
  }
  else {
    $result[$j]['amount'] += $entry['amount'];
  }
}

Diziniz store_id tarafından endeksli için Thrawn'ın cevabı üzerinde durmak, ne istediğiniz. Ne sonunda istiyorum:

    array (
        [1] => 100.00
        [2] => 10.00
    )

Sadece baştan bu inşa edilemez, ancak bu orijinal dizi yapısı ile çalışmak zorunda iseniz, bunu (en $stores diyelim):

    $totals = array();
    foreach ($stores as $store) {
        if (!array_key_exists($store['store_id'], $totals)) {
            $totals[$store['store_id']] = $store['amount'];
        }
        else {
            $totals[$store['store_id']] += $store['amount'];
        }
    }

Array_key_exists kontrol yapmak için yollar bir sürü var. empty ve isset olur kafi hem de.