
本文旨在提供一种使用PHP重构多维数组结构的实用方法。通过遍历原始数组,并根据object_type和object_id的值,将数据重新组织成嵌套的关联数组。最终结果将按照object_type分组,然后在每个object_type下,再按照object_id分组,从而实现更清晰的数据结构。
在处理复杂的数据结构时,原始数组的结构可能并不总是满足需求。有时,我们需要根据特定的字段(例如 object_type 和 object_id)对数组进行重新组织,以便更好地进行数据分析或展示。以下是如何使用PHP实现这种转换的方法。
实现方法
核心思路是遍历原始数组,并利用object_type和object_id的值作为新数组的键,将原始数据放入相应的位置。
立即学习“PHP免费学习笔记(深入)”;
以下是实现此功能的PHP代码:
<?php
$arr = [
[
'initiator_id' => 259, 'object_type' => 1, 'object_id' => 905,
'date' => '2021-11-16 06:24:16',
],
[
'initiator_id' => 259, 'object_type' => 1, 'object_id' => 917,
'date' => '2021-11-16 06:24:16',
],
[
'initiator_id' => 259, 'object_type' => 1, 'object_id' => 905,
'date' => '2021-11-16 04:54:54',
],
[
'initiator_id' => 259, 'object_type' => 1, 'object_id' => 905,
'date' => '2021-11-16 04:53:58',
],
[
'initiator_id' => 219, 'object_type' => 2, 'object_id' => 915,
'date' => '2021-11-16 04:53:58',
],
];
$result = [];
foreach ($arr as $item) {
$result['object_type'][$item['object_type']][$item['object_id']][] = $item;
}
print_r($result);
?>代码解释
示例输出
运行上述代码,将会得到如下结构的数组:
Array
(
[object_type] => Array
(
[1] => Array
(
[905] => Array
(
[0] => Array
(
[initiator_id] => 259
[object_type] => 1
[object_id] => 905
[date] => 2021-11-16 06:24:16
)
[1] => Array
(
[initiator_id] => 259
[object_type] => 1
[object_id] => 905
[date] => 2021-11-16 04:54:54
)
[2] => Array
(
[initiator_id] => 259
[object_type] => 1
[object_id] => 905
[date] => 2021-11-16 04:53:58
)
)
[917] => Array
(
[0] => Array
(
[initiator_id] => 259
[object_type] => 1
[object_id] => 917
[date] => 2021-11-16 06:24:16
)
)
)
[2] => Array
(
[915] => Array
(
[0] => Array
(
[initiator_id] => 219
[object_type] => 2
[object_id] => 915
[date] => 2021-11-16 04:53:58
)
)
)
)
)注意事项
总结
通过使用简单的循环和数组操作,我们可以轻松地根据 object_type 和 object_id 重构PHP多维数组,使其更易于管理和使用。这种方法在处理需要按特定字段分组的数据时非常有用。
以上就是PHP多维数组结构转换:根据object_id重构数组的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号