0

Here's a sample of data

Date  | Source | Amount
-----------------------
01A   | S1     | 12
01A   | S4     | 2
01A   | S7     | 134
02A   | S1     | 126
03A   | S4     | 10
02A   | S7     | 0
02A   | S1     | 3
02A   | S4     | 4
02A   | S7     | 5

The resulting array needs to look like:

Array
(
    [01A] => Array
        (
            [S1] => 12
            [S4] => 2
            [S7] => 134
        )
    [02A] => Array
        (
            [S1] => 126
            [S4] => 10
            [S7] => 0
        )
    [03A] => Array
        (
            [S1] => 3
            [S4] => 4
            [S7] => 5
        )
)

I've tried looking at pages such as PHP Adding multiple associative arrays to new array based on key, PHP multiple arrays to one associative array and Merge multiple associative arrays to a single array of associative arrays and playing around with code as below (not using the same data - but same theory) but it's not producing what I need. The code below just shows A and B

    $array = Array();
    $a=array( "ABC" => array("A"=>"RED","B"=>"GREEN"));
    $b=array( "ABC" => array("C"=>"BLUE","D"=>"YELLOW"));
    $array = $a + $b;
    echo '<pre>';
    print_r($array);
    echo '</pre>';
pee2pee
  • 3,619
  • 7
  • 52
  • 133
  • Is the original data in a database? If so which one? – RiggsFolly Sep 22 '17 at 09:38
  • Yes - it's a cut down version of MySQL – pee2pee Sep 22 '17 at 09:39
  • There are a lot of PHP [array functions](http://php.net/manual/en/ref.array.php) you can use. Or use a simple [`foreach`](http://php.net/manual/en/control-structures.foreach.php) loop to build the expected array. Have you tried anything? – axiac Sep 22 '17 at 09:40
  • That's why I am asking for - I'm not sure how to do it - I've tried – pee2pee Sep 22 '17 at 09:41
  • Then you should look up how to Pivot a Table [Here would be a good start](https://stackoverflow.com/questions/7674786/mysql-pivot-table) Then you can get MYSQL to do all the work for you – RiggsFolly Sep 22 '17 at 09:41
  • It's very cut down.... like only SELECT and WHERE allowed – pee2pee Sep 22 '17 at 09:43

2 Answers2

1

KISS

$result = array();
foreach($rows as $row)
{
    if(!isset($result[$row['Date']])) $result[$row['Date']] = array();
    $result[$row['Date']][$row['Source']] = $row['Amount'];
}
Michael M.
  • 189
  • 1
  • 7
1

Assuming you already have the data in the $input array, the code is as easy as:

$result = array();
foreach ($input as $row) {
    $date = $row['Date'];
    if (! array_key_exists($date, $result)) {
        $result[$date] = array();
    }

    $result[$date][$row['Source']] = $row['Amount'];
}

If you don't have the data in $input but you fetch it from the database just replace the line:

foreach ($input as $row) {

with something that matches your data retrieval loop, f.e.:

while ($row = mysqli_fetch_assoc($result)) {
axiac
  • 68,258
  • 9
  • 99
  • 134