Skip to content
Advertisement

Split assoc array by keys

I have data like this:

$movements = [
    array(
        "amount" => 100,
        "type" => "expense",
        "Dates" => "2020-01-01"
    ),
    array(
        "amount" => 100,
        "type" => "income",
        "Dates" => "2020-01-01" 
    ),
    array(
        "amount" => 200,
        "type" => "expense",
        "Dates" => "2020-02-01" 
    ),
    array(
        "amount" => 200,
        "type" => "income",
        "Dates" => "2020-02-01" 
    ),
    array(
        "amount" => 300,
        "type" => "income",
        "Dates" => "2020-03-01" 
    ),
    array(
        "amount" => 400,
        "type" => "expense",
        "Dates" => "2020-04-01" 
    ),
    array(
        "amount" => 400,
        "type" => "income",
        "Dates" => "2020-04-01" 
    ),
]

I want to separate it into 3 different arrays like so:

//This are my chart labels
$dates = ["2020-01-01","2020-02-01","2020-03-01"."2020-04-01"]

//This are my datapoints
$income = [100,200,300,400]
$expense = [100,200,0,400]

For the life of me i just cant seem to wrap my head around this today, I have tried doing loops and while/if using “array_colum()” but I cant get to add a 0 for the entry that does not have a matching date.

PS: I need the data in that format snice im charting it on chart.js within a Laravel view.

Any help is greatly appreciated.

Advertisement

Answer

$movements = [
    [ 'amount' => 100, 'type' => 'expense', 'Dates' => '2020-01-01' ],
    [ 'amount' => 100, 'type' => 'income', 'Dates' => '2020-01-01' ],
    [ 'amount' => 200, 'type' => 'expense', 'Dates' => '2020-02-01' ],
    [ 'amount' => 200, 'type' => 'income', 'Dates' => '2020-02-01' ],
    [ 'amount' => 300, 'type' => 'income', 'Dates' => '2020-03-01' ],
    [ 'amount' => 400, 'type' => 'expense', 'Dates' => '2020-04-01' ],
    [ 'amount' => 400, 'type' => 'income', 'Dates' => '2020-04-01' ],
];

$dates = array_values(array_unique(array_column($movements, 'Dates')));
$income = [];
$expense = [];

foreach ($dates as $date) {
  $item = array_values(array_filter($movements, fn($item) => $item['Dates'] === $date));
  $amount1 = $item[0]['amount'];
  $amount2 = count($item) === 2 ? $item[1]['amount'] : 0;
  $expense[] = $item[0] === 'expense' ? $amount1 : $amount2;
  $income[] = $item[0] === 'expense' ? $amount2 : $amount1;
}

print_r($dates);
print_r($income);
print_r($expense);

This will print:

Array
(
    [0] => 2020-01-01
    [1] => 2020-02-01
    [2] => 2020-03-01
    [3] => 2020-04-01
)
Array
(
    [0] => 100
    [1] => 200
    [2] => 300
    [3] => 400
)
Array
(
    [0] => 100
    [1] => 200
    [2] => 0
    [3] => 400
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement