0

this is my array now but I don't want like this

array:36 [▼
  "pentrose_50_rafhan_c_kgs" => 100
  "pentrose_50_rafhan_c_issued_kgs" => 300
  "pentrose_50_rafhan_c_rskg" => 99.1
  "pentrose_50_rafhan_c_amount" => 29730
  
]

This is my code:

foreach (array_combine($result, $filterred_chemical_keys) as $key => $chemical) {
    $arr = explode('_c_', $key);
    // dd($arr);
    $result[array_shift($arr)] = $arr;            
}

dd($result);

Please help to make array like this

array:36 [▼
    "pentrose_50_rafhan" => [
        "kgs" => 100
        "issued_kgs" => 300
        "rskg" => 99.1
        "amount" => 29730
    ]
]

I just explode via _c_ and make key parent and other keys as a child. I have tried many things like array_shift but nothing works for me. Any help, please?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43

2 Answers2

1

I guess you could just achieve this by using explode as you're doing already, I just wrapped it inside an array walk and then rebuilt another array.

$formattedArray = [];

array_walk($array, function($value, $key) use (&$formattedArray) {
    list($prefix, $newKey) = explode('_c_', $key);
    $formattedArray[$prefix][$newKey] = $value;
});

This gives the expected output below - see it working over at 3v4l.org:

array(1) {
  ["pentrose_50_rafhan"]=>
  array(4) {
    ["kgs"]=>
    int(100)
    ["issued_kgs"]=>
    int(300)
    ["rskg"]=>
    float(99.1)
    ["amount"]=>
    int(29730)
  }
}

Further reading:

Update: If you want to achieve it on one line

$newArray[explode('_c_', current(($keys = array_keys($array))))[0]] = array_map(fn($key) => [explode('_c_', $key)[1] => $array[$key]], $keys);
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • `list()` isn't the modern standard since "symmetric array destructuring" was implemented in PHP7.1. – mickmackusa Sep 15 '22 at 22:55
  • Explode will only ever have numeric key values, so I decided to use it for readability of the post. If the OP wants to access its index in their solution, that is down to them. I linked it as "further research" for said reason :D @mickmackusa – Jaquarh Sep 15 '22 at 22:59
1

A method using collections instead of array_functions

Inspired by https://laravel.com/docs/9.x/helpers#method-array-prependkeyswith

$data = [
     "pentrose_50_rafhan_c_kgs" => 100,
     "pentrose_50_rafhan_c_issued_kgs" => 300,
     "pentrose_50_rafhan_c_rskg" => 99.1,
     "pentrose_50_rafhan_c_amount" => 29730,
];
collect($data)
    ->groupBy(function($item, $key) {
        return Str::before($key, '_c_');
    }, preserveKeys: true)
    ->map
    ->mapWithKeys(function ($item, $key) {
        return [Str::after($key, '_c_')  => $item];
    })
    ->toArray();
[
    "pentrose_50_rafhan" => [
        "kgs" => 100,
        "issued_kgs" => 300,
        "rskg" => 99.1,
        "amount" => 29730,
    ],
]
RawSlugs
  • 520
  • 4
  • 11