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>';
6
  • Is the original data in a database? If so which one? Commented Sep 22, 2017 at 9:38
  • Yes - it's a cut down version of MySQL Commented Sep 22, 2017 at 9:39
  • There are a lot of PHP array functions you can use. Or use a simple foreach loop to build the expected array. Have you tried anything? Commented Sep 22, 2017 at 9:40
  • That's why I am asking for - I'm not sure how to do it - I've tried Commented Sep 22, 2017 at 9:41
  • Then you should look up how to Pivot a Table Here would be a good start Then you can get MYSQL to do all the work for you Commented Sep 22, 2017 at 9:41

2 Answers 2

1

KISS

$result = array();
foreach($rows as $row)
{
    if(!isset($result[$row['Date']])) $result[$row['Date']] = array();
    $result[$row['Date']][$row['Source']] = $row['Amount'];
}
Sign up to request clarification or add additional context in comments.

Comments

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)) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.