user20476491
user20476491

Reputation:

How to assign values in array based on array keys

How to modify an array based on the value as key?

array(
    array(
        "name" => "BIBAR",
        "cutoff" => 20220725,
        "totals" => 5614
    ),
    array(
        "name" => "BIBAR",
        "cutoff" => 20220810,
        "totals" => 5614
    ),
    array(
        "name" => "BIBAR",
        "cutoff" => 20220825,
        "totals" => 5614
    )
);

I tried the following but it's not working:

foreach($cutoffs as $catoff) {
    $ii = 0;
    $sums[$ii][$catoff] = array_filter($array, function($val){
        return $val['cutoff'] === $catoff ? $val['totals'] : $val;
    });
    $ii++;
}

My desired array:

array(
    '20221025' => array(
        12345,
        12343,
        24442
    ),
    '20221110' => array(
        3443,
        744334
    )
)

I'm stuck here for hours ... Please help

Upvotes: 0

Views: 89

Answers (2)

Mike
Mike

Reputation: 219

IF the "name" is irrelevant, I think also the previous answer should be fine. If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.

My code is:

$a = array(
    array(
        "name" => "BIBAR",
        "cutoff" => 20220725,
        "totals" => 5614
    ),
    array(
        "name" => "BIBAR",
        "cutoff" => 20220810,
        "totals" => 5614
    ),
    array(
        "name" => "BIBAR",
        "cutoff" => 20220725,
        "totals" => 1234
    )
);

print_r($a);


echo "\n================================\n\n";

$newArr = [];

foreach ($a as $k => $vArr) {
    // maybe some validation would be useful here, check if they keys exist
    $newArr[$vArr['cutoff']][] = $vArr['totals'];
}

print_r($newArr);

enter image description here

Upvotes: 0

Niaho
Niaho

Reputation: 34

function changeArr($data){
    $new = [];
    foreach ($data as $v){
        $new[$v['cutoff']][] = $v['totals'];
    }
    return $new;
}

Upvotes: 0

Related Questions