0

我被困住了。我有 2 个要组合的数组,忽略空值并返回一个字符串。如:

$Array1 ( [0] => [1] => Monday [2] => Wednesday [3] => Friday [4] => Sunday ) 
$Array2 ( [0] => [1] => 8am [2] => [3] => 10am [4] => [5] => 2pm [6] => [7] => 4pm ) 

返回:

周一上午 8 点,周三上午 10 点,周五下午 2 点,周日下午 4 点

提前致谢...

4

3 回答 3

2

尚不完全清楚您希望输出的格式,但array_filter()第一步是使用:

$a1 = array( null, 'Monday', 'Wednesday', 'Friday', 'Sunday' );
$a2 = array( null, '8am', null, '10am', null, '2pm', null, '4pm' );

$a1 = array_filter($a1);
$a2 = array_filter($a2);

这将删除空整。然后,您可以使用它foreach来构建您的输出。对于数组数组:

$out = array();
foreach ($a1 as $e) $out[] = array($e, array_shift($a2));

对于字符串数组:

$out = array();
foreach ($a1 as $e) $out[] = $e.' '.array_shift($a2);

演示显示两种输出类型:http ://codepad.org/ITZJH4RL

于 2012-04-18T17:49:06.487 回答
2
$periods = array();
foreach (array_combine(array_filter($Array1), array_filter($Array2)) as $day => $hour) {
  $periods[] = $day . ' ' . $hour;
}
echo implode(', ', $periods);
于 2012-04-18T17:42:54.373 回答
1

一种肮脏的方式来做到这一点,但是..

//Your arrays:
$Array1 = array( null , Monday, Wednesday, Friday, Sunday) 
$Array2 = array(null, 8am, null, 10am,null, 2pm, null, 4pm)
$Array3 =();
foreach($Array2 as $key=>$val):
    if($val != ''):
        array_push($Array3, $val);
    endif;
endforeach;

// This assumes you have the same number of values in each array
foreach( $Array1 as $key=>$val):
   $Array1[$key] = $Array1[$key] . " " . $Array3[$key];
endforeach;

var_dump($Array1);

试一试,如果您有任何错误,请告诉我。

编辑:将示例数组转换为实际数组,而不仅仅是从示例中列出它们。

于 2012-04-18T17:50:19.077 回答