2013-06-21 75 views
0

我試圖想出在特定自定義字段中的所有值的單個數組。這些值本身也是數組。我嘗試了各種數組函數,但沒有遇到正確的組合或正確的組合。這裏是我的代碼至今:從自定義字段中的數組中提取值

$args = array(
    'post_type' => 'match_report', 
    'post_status' => 'publish', 
    'meta_query' => array(
    'relation' => 'OR', 
     array(
      'key' => 'report_home-scorers' 
     ), 
     array(
      'key' => 'report_away-scorers' 
     ) 
    ) 
); 

$reportscore = new WP_Query($args); 
$scorersResults = array(); 

if ($reportscore->have_posts()) { 
    while ($reportscore->have_posts()) { 
     $reportscore->the_post(); 

$homescorers = get_post_meta($post->ID,'report_home-scorers',false); 
$awayscorers = get_post_meta($post->ID,'report_away-scorers',false);    

foreach ($homescorers as $homescorer){ 
array_push($scorersResults, $homescorer); 
} 
foreach ($awayscorers as $awayscorer){ 
array_push($scorersResults, $awayscorer); 
} 
?> 

<?php } wp_reset_postdata(); //endif 
}//endwhile 

$scorerResults = remove_empty($scorersResults); 

function remove_empty($array) { 
return array_filter($array, '_remove_empty_internal'); 
} 

function _remove_empty_internal($value) { 
return !empty($value) || $value === 0; 
} 

在這裏我得到什麼,如果我print_r($scorerResults);

Array 
(
[1] => Array 
    (
     [0] => 1 
     [1] => 63 
    ) 

[2] => Array 
    (
     [0] => 263 
     [1] => 195 
    ) 

[3] => Array 
    (
     [0] => 
    ) 

[4] => Array 
    (
     [0] => 
    ) 
) 

我只是想在一個陣列內部數組的值。

回答

0

假設你希望$scoreResults陣列最終成爲array(1,63,263,195)你可以使用array_reduce功能是這樣的:

function gatherScores($lhs, $rhs) { 
    foreach ($rhs as $key => $value) 
    if ($value) 
     $lhs[] = $value; 
    return $lhs; 
} 

$scorerResults = array_reduce($scorerResults, "gatherScores", array()); 

我不知道什麼是空值在你的第三和第四陣列,以及它們如何應該被處理,所以你可能需要改變if ($value)的條件來檢查不同的東西。就目前而言,它顯然也會過濾掉零分。

+0

這正是我想要的。我實際上認爲我不得不在最後運行另一個函數來刪除空值,所以這很有用。我包含了一個if語句,以避免有一個無效的參數:'if(!empty($ lhs)||!empty($ rhs))'謝謝! – mantis