Group 2d array’s row data by one column and sum another column within each group to produce a reduced 2d array

Just loop trough the rows, and add up the quantities in a different array indexed by the dd values. $in = array(array()); // your input $out = array(); foreach ($in as $row) { if (!isset($out[$row[‘dd’]])) { $out[$row[‘dd’]] = array( ‘dd’ => $row[‘dd’], ‘quantity’ => 0, ); } $out[$row[‘dd’]][‘quantity’] += $row[‘quantity’]; } $out = array_values($out); // … Read more

Group array data on one column and sum data from another column to form a flat associative array

So, first you need $amountsArray to get assigned the values you listed, somehow. Then: $bankTotals = array(); foreach($amountsArray as $amount) { $bankTotals[$amount[‘name’]] += $amount[‘amount’]; } Output: (Demo) Warning: Undefined array key “Bank BRI” Warning: Undefined array key “Bank BCA” Warning: Undefined array key “Bank CIMB Niaga” Warning: Undefined array key “Bank BNI” Warning: Undefined array … Read more

2D Array indexing – undefined behavior?

It’s undefined behavior, and here’s why. Multidimensional array access can be broken down into a series of single-dimensional array accesses. In other words, the expression a[i][j] can be thought of as (a[i])[j]. Quoting C11 ยง6.5.2.1/2: The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). This means the above is identical … Read more

Get the indices of N highest values in an ndarray

You can use numpy.argpartition on flattened version of array first to get the indices of top k items, and then you can convert those 1D indices as per the array’s shape using numpy.unravel_index: >>> arr = np.arange(100*100*100).reshape(100, 100, 100) >>> np.random.shuffle(arr) >>> indices = np.argpartition(arr.flatten(), -2)[-2:] >>> np.vstack(np.unravel_index(indices, arr.shape)).T array([[97, 99, 98], [97, 99, 99]]) … Read more

PHP convert nested array to single array while concatenating keys?

Something like this: function makeNonNestedRecursive(array &$out, $key, array $in){ foreach($in as $k=>$v){ if(is_array($v)){ makeNonNestedRecursive($out, $key . $k . ‘_’, $v); }else{ $out[$key . $k] = $v; } } } function makeNonNested(array $in){ $out = array(); makeNonNestedRecursive($out, ”, $in); return $out; } // Example $fooCompressed = makeNonNested($foo);