【问题标题】:Combine foreach output data合并 foreach 输出数据
【发布时间】:2017-09-09 12:26:26
【问题描述】:

我正在做一个项目,根据具体情况,我需要将一些输出数据组合成一个变量。

*$array 包含不同的用户信息

$array[]= array(
    'ts3_uuid' => $value['client_unique_identifier'],
    'channel_name' => $value['client_unique_identifier'],
    'steam_id' => $steam_id,
    'ts3_clid' => $value['clid'],
    'channel_id' => $value['cid'],
    'steam_name' => htmlspecialchars($steam_name),
    'csgo_rank' => $csgo_rank,
    'steam_status' => $steam_official_status,
    'last_steam_connection' => $timestamp,
    'steam_vac_status' => $result_steam_ban,
    'csgo_played_time' => $total_tiempo_jugado,
    'csgo_hs_porcentage' => $hs_porcent,
    'csgo_kdr' => $kdr
    );
foreach ($array as $data) {
    $channel_description = $data['steam_name'];
}

这是我脑海中的结构......

if (the channel_id of different users are EQUAL){
combine their $data['steam_name'] into the $channel_description variable and 
then, for example, echo it.
}

希望你能帮助我:-)

【问题讨论】:

  • 那么,问题出在哪里?
  • 试试这个数据 += newdata;
  • 问题是我不知道如何将他们的数据“连接”到一个变量中,如果他们的 channel_id 是 EQUAL...
  • Rajendran Nadar 你能举个例子吗?

标签: php arrays foreach


【解决方案1】:

可以处理数组中的所有数据:

  foreach($array as $user_index=>$user_array)
        {
        foreach($user_array as $array_index=>$array_data)
              {
              $channel_id_array[$user_index]=$array_data['channel_id'];
              if(in_array($array_data['channel_id'],$channel_id_array))
                     {
                     echo'this channel_id is not unique <br/>';
                     echo 'first array with equal chanel_id';
                     print_r($array[$user_index]);
                     echo 'second array with equal channel id';  
                     print_r($array_data);
                     }
              }
         }

【讨论】:

  • if($array_data['channel_id'],in_array($channel_id_array)) --> 语法错误,意外','
  • 试试这个方法,if(in_array($array_data['channel_id'], $channel_id_array))
  • 错误现已修复。
【解决方案2】:

使用一个辅助数组和函数找到相同的channel_id 并存储它的steam_name!在php数组中,调用相同的索引不是创建新数组!所以尝试将channel_id 设置为索引键。

$result = findSameChannelId($array);

foreach($result as $data) {
    echo $data["channel_description"]."<br>";
}

function findSameChannelId($array) {
    foreach ($array as $key => $value) {
        if(!isset($channel[$value["channel_id"]])) {
            $channel[$value["channel_id"]] = array("channel_description"=>"");  
        } 
        $channel[$value["channel_id"]]['channel_description'] .= $value["steam_name"];  
    }
    return $channel;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多