I am trying to group my array values based on the array keys then print the result in the UI.
I am stucked here for hours now.
Here is the array I need to format,
Array
(
[checklist1] => major
[result_audit1] => 1
[checklist2] => minor
[result_audit2] => 2
[checklist3] => pico
[result_audit3] => 3
[checklist4] => goodpoints
[result_audit4] => 4
[submit] => Submit Now
)
Here is what I have tried so far but it is misaligned and not a proper result of the array.
foreach($n_data as $key => $data)
{
$array['checklist'][$i] = array(
'selected' => $n_data[$key],
'result_audit' => $n_data[$key]
);
$i++;
}
Here is what I desired array:
Array
(
[checklist] => Array
(
[0] => Array
(
[selected] => major
[result_audit] => 1
[origin] => checklist1
)
[1] => Array
(
[selected] => minor
[result_audit] => 2
[origin] => checklist2
)
))
Thanks for the help.
5
Answers
Here is a way to do it:
Output:
You can try something like this:
Demo
I tried something that can result what you need
Here I iterate through
$datas
array and check if the key contains the string "checklist" and add a new entry to$array['checklist']
array with the desired format. The result_audit value is obtened by concatenating the string "result_audit" with the last character of the current key (index number).Looking at the order and the alignment of your array, you can use
array_chunk
to split the array into chunks of 2 and then usearray_walk
to add the keys as you desire. Usearray_splice
to get rid of thesubmit
key. Below is the compact code for the same.Snippet:
Live Demo
Output: