0

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

2
  • Please check and edit your question, the formatting looks broken. Also consider to write what the not-expected outcome is, just a "not working" is incomplete. See as well help center. Commented Nov 20, 2022 at 11:18
  • 3
    Please use var_export() instead of print_r() for dumping. Commented Nov 20, 2022 at 11:19

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Please don't just dump code as an answer, always add some explanation of what may have been the problem and how your code solves OP's problem so others can learn. Thanks

Your Answer

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