This is my array:
Array
(
[F] => 09:00 - 18:00
[M] => 09:00 - 18:00
[Th] => 09:00 - 18:00
[W] => 09:00 - 18:00
[T] => 09:00 - 18:00
[Su] => RD
[Sa] => RD
)
and I want to produce this output:
MTWThF 9:00 - 18:00 SaSu RD
this is my code:
array_s=array(
F => 09:00 - 18:00
M => 09:00 - 18:00
Th => 09:00 - 18:00
W => 09:00 - 18:00
T => 09:00 - 18:00
Su => RD
Sa => RD
)
asort($array_s);
$temp_s = '';
foreach($array_s as $key => $value){
if($temp_s == null){
$temp_s = $value; //first array
$temp_day = $key;
$res_day .= $temp_day;
}else{
if($value == $temp_s){
$res_day .= $key;
}else{
echo $res_day ." ". $temp_s;
$res_day = null;
$temp_s = $value;
$temp_day = $key;
$res_day .= $temp_day;
}
}
but the output is this:
FMThWT 09:00 - 18:00 May be I did something wrong but I dont know how to fix error. thanks
Many ways to do something like this. Here's an example:
foreach(array_values($array_s) as $value) {
foreach($array_s as $key => $current) {
if($value != $current)
continue;
if(!array_key_exists($value, $output))
$output[$value] = array();
if(!in_array($key, $output[$value]))
$output[$value][] = $key;
}
}
This gives you a structured array like this:
Array
(
[09:00 - 18:00] => Array
(
[0] => F
[1] => M
[2] => Th
[3] => W
[4] => T
)
[RD] => Array
(
[0] => Su
[1] => Sa
)
)
Then, you can output it like this:
foreach($output as $key => $current) {
echo implode('', $current) . ' ' . $key . ' ';
}
Weird way to output data, but that'll give you:
FMThWT 09:00 - 18:00 SuSa RD
... it's not in the order you want, but the best way to achieve that order is to fix it where you create the array (as it's obviously a date related thing) - harder to sort that you've created it like that than it is to sort it at the beginning. If you decide that you'd rather sort it here, have a look at this post and use his example.
Output demo: https://eval.in/78517
Documentation
After the foreach is done, you need to echo what's left:
array_s=array(
F => 09:00 - 18:00
M => 09:00 - 18:00
Th => 09:00 - 18:00
W => 09:00 - 18:00
T => 09:00 - 18:00
Su => RD
Sa => RD
)
asort($array_s);
$temp_s = '';
foreach($array_s as $key => $value){
if($temp_s == null){
$temp_s = $value; //first array
$temp_day = $key;
$res_day .= $temp_day;
}else{
if($value == $temp_s){
$res_day .= $key;
}else{
echo $res_day ." ". $temp_s;
$res_day = null;
$temp_s = $value;
$temp_day = $key;
$res_day .= $temp_day;
}
}
}
echo $res_day ." ". $temp_s;