我有2个关联。具有相同结构但只有一个ID的数组是相同的。每当特定ID相同时,我需要从IncludeArray向MainArray添加内容。
以下是数组的示例(MainArray最多可容纳100个或更多项,该示例仅包含部分实际内容):
$MainArray = Array
(
[0] => Array
(
[item_id] => 1
[name] => Test1
[helptxt] => Helptext for item-id 1.
[type_id] => 1 #could be the same for many other items!!
)
[1] => Array
(
[item_id] => 2
[name] => Test2
[helptxt] => Helptext for item-id 2.
[type_id] => 2 #could be the same for many other items!!
)
and a lot more Arrays
)
$IncludeArray = Array
(
[0] => Array
(
[type_id] => 1
[typetitle] => Number
[typedesc] => Description Text type_id 1
)
[1] => Array
(
[type_id] => 2
[typetitle] => Value
[typedesc] => Description Text type_id 2
)
)
所需的新数组应为:
$NewMainArray = Array
(
[0] => Array
(
[item_id] => 1
[name] => Test
[helptxt] => Helptext for item-id 1.
[type_id] => 1
[typetitle] => Number
[typedesc] => Description Text type_id 1
)
[1] => Array
(
[item_id] => 2
[name] => Test2
[helptxt] => Helptext for item-id 2.
[type_id] => 2
[typetitle] => Value
[typedesc] => Description Text type_id 2
)
And so on with all other items in the Array.
)
因此,每次在$ MainArray中找到type_id时,[typetitle] + [typedesc]的内容应该添加到$ NewMainArray。
我的大多数测试都以仅合并Arrays或仅添加$ IncludeArray一次结束。甚至我的论坛搜索都没有让我找到解决方案。
数组是从2个单独的DB-Requests创建的,我无法加入(已尝试多次尝试)。这与不同的WHERE和AND子句有关,这些子句不适用于已连接的请求。
我希望有一种聪明的方法来获得所需的$ NewMainArray。顺便说一句,我使用PHP4,我是PHP的新手(至少对于这种问题)。
非常感谢你的帮助。
答案 0 :(得分:1)
试试这个:
/**
* Simulates relational table behaviour by joining data matching an ID value.
* Works with single-nested arrays.
*
* @author Joel A. Villarreal Bertoldi
*
* @param $source array The source array.
* @param $include_to_row array The row where we'll deposit the joined data.
* @param $match string Unique id field name.
*
* @return array Row with joined data.
*/
function includeFromArray($source, $include_to_row, $match)
{
foreach ($source as $source_row)
{
if ($source_row[$match] == $include_to_row[$match])
{
foreach ($source_row as $source_column_key => $source_column_value)
{
$include_to_row[$source_column_key] = $source_column_value;
}
}
}
return $include_to_row;
}
for ($ma = 0; $ma < count($MainArray); $ma++)
$NewMainArray[$ma] = includeFromArray($IncludeArray, $MainArray[$ma], "type_id");
结果:
Array
(
[0] => Array
(
[item_id] => 1
[name] => Test1
[helptxt] => Helptext for item-id 1.
[type_id] => 1
[typetitle] => Number
[typedesc] => Description Text type_id 1
)
[1] => Array
(
[item_id] => 2
[name] => Test2
[helptxt] => Helptext for item-id 2.
[type_id] => 2
[typetitle] => Value
[typedesc] => Description Text type_id 2
)
)
答案 1 :(得分:-1)
看一下array_merge_recursive函数;)
http://nl2.php.net/manual/en/function.array-merge-recursive.php