[英]add field and value to array while looping through?
我有以下 2 arrays,我需要根據第二個的 ID 值添加第一個的值作為鍵,以便我可以訂購第二個數組 DESC:
觀看次數:
Array ( [1851] => 12 [14341] => 7 [17834] => 3 )
我有以下數組 object:
$most_seen_list:
Array (
[0] => WP_Post Object (
[ID] => 17834
[post_date] => 2021-10-20 16:01:50
[post_date_gmt] => 2021-10-20 21:01:50
)
[1] => WP_Post Object (
[ID] => 14341
[post_date] => 2021-06-01 17:57:00
[post_date_gmt] => 2021-06-01 22:57:00
)
[2] => WP_Post Object (
[ID] => 1851
[post_date] => 2021-02-13 18:09:00
[post_date_gmt] => 2021-02-13 23:09:00
)
)
與下一個 foreach 我正在經歷它,我想改變[0]..[1]..[3]
具有我從另一個數組中獲得的值的鍵:
foreach ($most_seen_list as $key => $value) {
$newResult[$value->ID];
}
預期 output:
Array (
[12] => WP_Post Object (
[ID] => 1851
[post_date] => 2021-02-13 18:09:00
[post_date_gmt] => 2021-02-13 23:09:00
)
[7] => WP_Post Object (
[ID] => 14341
[post_date] => 2021-06-01 17:57:00
[post_date_gmt] => 2021-06-01 22:57:00
)
[3] => WP_Post Object (
[ID] => 17834
[post_date] => 2021-10-20 16:01:50
[post_date_gmt] => 2021-10-20 21:01:50
)
)
我假設您已經對$views
數組進行了排序。 因此,您需要使用內部循環處理每個$most_seen_list
對象數組以找到正確的對象
$views = Array ( 1851 => 12, 14341 => 7, 17834 => 3 );
$most_seen_list = Array (
(Object) [ 'ID' => 17834,'post_date' => '2021-10-20 16:01:50', 'post_date_gmt' => '2021-10-20 21:01:50',
],
(Object) [ 'ID' => 14341, 'post_date' => '2021-06-01 17:57:00', 'post_date_gmt' => '2021-06-01 22:57:00'
],
(Object) ['ID' => 1851, 'post_date' => '2021-02-13 18:09:00', 'post_date_gmt' => '2021-02-13 23:09:00'
]
);
$new = [];
//get the ID'2 in the predefined order set in $views
foreach ( $views as $key=>$val) {
// for each view find the correct object in $most_seen_list
foreach( $most_seen_list as $obj) {
if ( $obj->ID == $key ) {
$new[$val] = $obj;
break; // terminate this iteration
}
}
}
print_r($new);
結果
Array
(
[12] => stdClass Object
(
[ID] => 1851
[post_date] => 2021-02-13 18:09:00
[post_date_gmt] => 2021-02-13 23:09:00
)
[7] => stdClass Object
(
[ID] => 14341
[post_date] => 2021-06-01 17:57:00
[post_date_gmt] => 2021-06-01 22:57:00
)
[3] => stdClass Object
(
[ID] => 17834
[post_date] => 2021-10-20 16:01:50
[post_date_gmt] => 2021-10-20 21:01:50
)
)
如果您不需要查看量作為鍵(如果某些查看量無論如何都相同,這可能會出現問題),您可以使用以下內容以正確的順序對帖子進行排序。
// sort asc on views
usort($most_seen_list, function($postA, $postB) use ($views) {
return $views[$postA->ID] <=> $views[$postB->ID];
});
$most_seen_list = array_reverse($most_seen_list); // reverse the order, so most viewed is first
在此之后,您仍然可以使用以下方法獲取每個帖子的視圖:
$views[$oneOfThePosts->ID];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.