【问题标题】:PHP - join items in array based on their indexPHP - 根据索引加入数组中的项目
【发布时间】:2022-01-06 00:03:14
【问题描述】:

我不确定这个问题是否有意义,但我有以下数组:

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 
)

我想加入具有匹配索引的项目。例如,column_0_title & column_0_content 将成为一个单独的嵌套数组

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

【问题讨论】:

  • 使用explode('_', $key)获取原始密钥的部分。然后将它们用作嵌套数组元素的键来分配。
  • $result[$parts[1]][$parts[2]] = $value
  • @Barmar 很抱歉,您能否发布一个完整的示例,我不完全理解。
  • StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • 我以为我已经给出太多提示了。

标签: php for-loop foreach


【解决方案1】:

使用foreach 在数组内部循环,然后使用explode 函数从键中提取索引和键名,然后根据您提取的索引和键名将值添加到新数组中

<?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);
?>

【讨论】:

  • 谢谢!我不确定爆炸功能是否仍然需要 foreach,我非常感谢您的参考,这很好
猜你喜欢
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2011-11-29
  • 2021-02-26
  • 2021-08-03
  • 1970-01-01
  • 2011-11-17
  • 2023-01-06
相关资源
最近更新 更多