Reputation: 1
I am stuck. I have 2 arrays that I want to combine, ignoring the empty values, and return a string. Such as:
$Array1 ( [0] => [1] => Monday [2] => Wednesday [3] => Friday [4] => Sunday )
$Array2 ( [0] => [1] => 8am [2] => [3] => 10am [4] => [5] => 2pm [6] => [7] => 4pm )
to return:
Monday 8am, Wednesday 10am, Friday 2pm, Sunday 4pm
Thanks in advance...
Upvotes: 0
Views: 2234
Reputation: 581
Kind of a dirty way to do it but..
//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);
Give it a shot and let me know if you get any errors.
Edit: Turned example arrays into actual arrays instead of just listing them out from the example.
Upvotes: 1
Reputation: 7157
It's not entirely clear what format you want the output in, but using array_filter()
is the first step:
$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);
This removes the null entires. You can then use foreach
to build your output. For an array of arrays:
$out = array();
foreach ($a1 as $e) $out[] = array($e, array_shift($a2));
For an array of strings:
$out = array();
foreach ($a1 as $e) $out[] = $e.' '.array_shift($a2);
Demo showing both output types: http://codepad.org/ITZJH4RL
Upvotes: 2
Reputation: 63542
$periods = array();
foreach (array_combine(array_filter($Array1), array_filter($Array2)) as $day => $hour) {
$periods[] = $day . ' ' . $hour;
}
echo implode(', ', $periods);
Upvotes: 2