因此,为了获得团队名称的团队颜色,您应该重新构建您的$team_info数组,以便更快地访问,其中键是团队名称,值是团队颜色。我们首先使用team names检索所有array_column,然后使用team_color检索相同的array_combine()。我们稍后使用<?php
$team_info = array_combine(array_column($team_info,'team_name'),array_column($team_info,'team_color'));将第一个数组值作为键,将第二个数组值作为这些键的值。像下面这样的东西 -
Array
(
[0] => Array
(
[team_name] => team1
[team_color] => red
)
[1] => Array
(
[team_name] => team2
[team_color] => blue
)
[2] => Array
(
[team_name] => team3
[team_color] => green
)
[3] => Array
(
[team_name] => team4
[team_color] => yellow
)
)
上面的代码重构了它:
Array
(
[team1] => red
[team2] => blue
[team3] => green
[team4] => yellow
)
至
echo $team_info[$team_cookie]
现在,你可以做team_cookie来获得球队的颜色。
更新:
如果您的要求是仅搜索单个团队的颜色,那么您可以使用简单的foreach循环并检查team_color是否与任何团队名称匹配,然后将其<?php
$team_color = "";
foreach($team_info as $each_team){
if($each_team['team_name'] === $team_cookie){
$team_color = $each_team['team_color'];
break;
}
}
echo $team_color;分配给变量。
if(isset($_COOKIE['TEAM'])) {
$team_cookie = $_COOKIE['TEAM'];
$team_info=Array (
'0' => Array (
'team_name' => 'team1',
'team_color' => 'red'
),
'1' => Array (
'team_name' => 'team2',
'team_color' => 'blue'
),
'2' => Array (
'team_name' => 'team3',
'team_color' => 'green'
),
'3' => Array (
'team_name' => 'team4',
'team_color' => 'yellow'
)
);
$color = "";
foreach ($team_info as $team_info) {
if($team_cookie == $team_info['team_name'] ) {
// Do something
$color = $team_info['team_color'];
break;
}
}
echo $color;
}
但是,如果要搜索多个团队名称,请通过重组数组执行上述操作。您还可以将它们保持在会话中以获得更好的性能时间。