[英]PHP search array and add content on position where id's are equal
我有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中。
我的大多數測試都以僅合並Array或僅添加一次$ IncludeArray結束。 甚至我的論壇搜索也無法幫助我解決。
數組是從2個單獨的DB請求創建的,我無法加入(已經嘗試了幾次)。 這與不同的WHERE和AND子句有關,這些子句不適用於聯接的請求。
我希望有一個聰明的方法來獲取所需的$ NewMainArray。 順便說一句,我使用PHP4,而且我是PHP的新手(至少針對這種問題)。
非常感謝你的幫助。
嘗試這個:
/**
* 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
)
)
看一下array_merge_recursive函數;)
http://nl2.php.net/manual/en/function.array-merge-recursive.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.