Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – join items in array based on their index

I’m not sure if this question makes sense, but I have the following array:

Array ( 
    [columns_0_title] => qasdf 
    [columns_0_content] => zxcv 
    [columns_1_title] => Title 1 
    [columns_1_content] => content 1 
    [columns_2_title] => Title 2 
    [columns_2_content] => content 2 
    [columns_3_title] => 1 
    [columns_3_content] => 2 
    [columns_4_title] => asdf 
    [columns_4_content] => 7 
)

And I’d like to join the items with matching indexes. Example, column_0_title & column_0_content would become a separate nested array

Array ( 
    [
        [title] => qasdf 
        [content] => zxcv 
    ]
    [
        [title] => Title 1 
        [content] => content 1 
    ]
    [
        [title] => Title 2 
        [content] => content 2 
    ]
    [
        [title] => 1 
        [content] => 2 
    ]
    [
        [title] => asdf 
        [content] => 7
    ] 
)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Loop inside array using foreach and then extract index and key name from the key using explode function and then add the value to new an array based on the index and key name you extracted

<?php
$arr = [
    "columns_0_title" => "title 0",
    "columns_0_content" => "content 0",
    "columns_1_title" => "title 1",
    "columns_1_content" => "content 1",
    "columns_2_title" => "title 2",
    "columns_2_content" => "content 2",
];
$new_arr = [];
foreach ($arr as $key => $value) {
    $index_arr = explode("_", $key);
    $new_arr[$index_arr[1]][$index_arr[2]] = $value;
}
var_dump($new_arr);
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading