2015-04-21 52 views
0

我有Array1为Wordpress自定义帖子类型提取所有条目,并从另一个表中获取Array2,以显示特定用户是否看到该帖子类型。如果Array1的ID为,则Array2的PageID相同,则将[Started] & [Finished]字段从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

包括你对这个问题的尝试以及任何来自这些尝试的错误。 – Epodax

+0

有没有可能在SQL级别上使用JOIN执行而不是合并数组?这可能是更好的解决方案。 – Stepashka

+0

Stepashka,在大多数情况下,加入将是一件坏事,并没有完美的解决方案:) –

回答

1

是这样的?

$array3 = array(); 
foreach($array1 as $arr1) 
{ 
    foreach($array2 as $arr2) 
    { 
     if($arr1["ID"] == $arr2["PageID"]) 
     { 
     $array3[] = array($arr1["Started"], $arr2["Finished"]); 
     } 
    } 
} 
+0

没有太多的其他解决方案。 唯一的另一种方法是通过array_map调用将“PageID”键重新映射为“ID”,并在两个数组上使用array_merge_recursive()。 – Flunch

0

array_combine()不是正确的功能。

你的情况,你需要使用foreach循环来遍历你的第一个数组的值,并将它们与你的第二个数组进行比较。

您也需要重新安排阵列2,这样就可以使用的pageID关键方便地访问了startedfinished值:

$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']]); 
} 
0

你可以尝试第一个循环以使阵列“ID”匹配,然后组合两个阵列

foreach($array2 as $key=>$value) 
    { 
     $value['ID'] = $value['PageId']; 
     unset($value['PageId']); 
     $array2[$key] = $value; 
    } 

$array3 = array_merge_recursive($array1,$array2); 
+0

如果您可以在两个查询中的任何一个上使用SQL ALIAS来确保两侧的“ID”键相同,然后只使用array_merge_recursive – Flunch

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' 
    "); 
相关问题