duanji9378 2013-12-11 04:39
浏览 5
已采纳

数组获取具有相似值的键

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

  • 写回答

2条回答 默认 最新

  • dongpaozhi5734 2013-12-12 04:28
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi