从自定义字段中的数组中提取值

时间:2013-06-21 22:00:17

标签: arrays nested

我正在尝试在特定自定义字段中提供所有值的单个数组。值本身也是数组。我已经尝试过各种各样的数组函数,但没有遇到正确的组合或正确的组合。这是我到目前为止的代码:

$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] => 
    )
)

我只想要数组内部数组中的值。

1 个答案:

答案 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)条件以检查不同的内容。目前它显然也会过滤掉零分。

相关问题