我有Array1拉取Wordpress自定义帖子类型的所有条目,我有另一个表格中的Array2,显示特定用户是否看过该帖子类型。如果Array1&的ID Array2的PageID是相同的,然后添加[Started]&从Array2到Array1的[已完成]字段。基本上我想将它们组合成Array3。我已经使用array_combine尝试了许多不同的解决方案,但无法获得我正在寻找的结果。
Array1 (
[0] => stdClass Object ( [ID] => 75 [post_title] => Test Training Video )
[1] => stdClass Object ( [ID] => 80 [post_title] => Test 2 )
[2] => stdClass Object ( [ID] => 85 [post_title] => Test 2 ) )
Array2 (
[0] => stdClass Object ( [PageID] => 75 [Started] => 1 [Finished] => 1 )
[0] => stdClass Object ( [PageID] => 80 [Started] => 1 [Finished] => 0 ) )
Array3 (
[0] => stdClass Object ( [ID] => 75 [post_title] => Test Training Video [Started] => 1 [Finished] => 1 )
[1] => stdClass Object ( [ID] => 80 [post_title] => Test 2 [Started] => 1 [Finished] => 0 )
[2] => stdClass Object ( [ID] => 85 [post_title] => Test 2 ) )
答案 0 :(得分:1)
这样的东西?
$array3 = array();
foreach( $array1 as $arr1 )
{
foreach( $array2 as $arr2 )
{
if( $arr1["ID"] == $arr2["PageID"] )
{
$array3[] = array( $arr1["Started"], $arr2["Finished"] );
}
}
}
答案 1 :(得分:0)
array_combine()不是正确的功能。
在您的情况下,您需要使用foreach循环来遍历第一个数组的值,并将它们与第二个数组进行比较。
您还需要重新排列数组2,以便您可以使用pageID作为键轻松访问started
和finished
的值:
$pageMap = array();
foreach($array2 as $entry) {
$pageMap[$entry['PageID']] = array('started' => $entry['Started'], 'finished' => $entry['Finished']);
}
然后你可以这样做:
$combined_array = array();
foreach($array1 as $post) {
if(!isset($pageMap[$post['ID']])) continue; // do nothing if there are no started/finished entries.
$combined_array[$post['ID']] = array_merge($post, $pageMap[$post['ID']]);
}
答案 2 :(得分:0)
您可以尝试第一个循环来制作阵列" ID"匹配然后组合两个数组
foreach( $array2 as $key=>$value )
{
$value['ID'] = $value['PageId'];
unset($value['PageId']);
$array2[$key] = $value;
}
$array3 = array_merge_recursive($array1,$array2);
答案 3 :(得分:0)
在尝试发布的解决方案后,我决定在我的$ wpdb-> get_results sql语句中进行更改,而不是使用2个不同的sql语句,然后组合2个不同的数组。在这篇文章的帮助下 - SQL query to join two tables despite the other table may not have values,我能够使用以下内容来获得所需的结果。
$oneBigQuery = $wpdb->get_results("SELECT a.ID, a.post_title, b.PageID, b.Started, b.Finished
FROM $wpdb->posts AS a
LEFT JOIN exampleTableName AS b
ON a.ID = b.PageID
AND b.UserID = 3
WHERE a.post_type = 'custom-post-type'
");