Home > Mobile >  PHP - join items in array based on their index
PHP - join items in array based on their index

Time:01-06

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
    ] 
)

CodePudding user response:

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);
?>
  •  Tags:  
  • Related