Foreach用于多维数组



我有一个多维数组:

Array (
  [0] => Array (
    [0] => Kolkata Knight Riders v Delhi Daredevils
    [1] => Kolkata
  ) 
  [1] => Array (
    [0] => Royal Challengers Bangalore v Mumbai Indians
    [1] => Bangalore
  )
  [2] => Array (
    [0] => Sunrisers Hyderabad v Pune Warriors 
    [1] => Hyderabad (Deccan)
  ) 
  [3] => Array (
    [0] => Delhi Daredevils v Rajasthan Royals 
    [1] => Delhi
  )
  ... 3 more elements
)

我想:

  • explode基于"v"的数组元素的每个第一个元素,这样我可以从Team B.中分离team A(例如array[0][0]分离Kolkata Knight RidersDelhi Daredevils)。
  • 创建一个新的数组,我想从两个爆炸数组中删除团队名称之间的空格(例如Sunrisers Hyderabad变成SunrisersHyderabad)。

我试过下面的代码:

$i = 0;
foreach($match1 as $value){
    $teams[$i] = explode(' v ', $value[0]); // Exploding teams
    $teams[$i] = strip_tags($teams[$i], 'a'); // Eliminating html
    $teamA[] = explode(' ', $team[$i][0]); // Eliminating Space in Team Name
    $teamA[] = trim($match2[$i]); // Removing white spaces
    $teamB[] = str_replace(' ', '', $team[$i][1]); // Trying Str_Replace method
    $teamB[] = trim($match3[$i]); // Removing White Spaces
    $i++;
}

上面的代码似乎不能满足我的所有要求。有没有有用的代码?

首先:请为变量使用逻辑名称,如果您使用match, real_match, match1, match2等变量名称,您的脚本将变得不可读。

echo '<pre>';
$data = array(
    array(
        'Kolkata Knight Riders v Delhi Daredevils',
        'Kolkata',
    ),
    // ...
);
foreach ($data as $match) {
    $teams = explode(' v ', $match[0]);
    $teams = array_map(function ($team) {
        return trim(str_replace(' ', '', $team));
    }, $teams);
    // do something with the 2 normalized teams in $teams
    var_dump($teams);
}

相关内容

  • 没有找到相关文章