[英]PHP Associative Arrays - how to match up values based on a condition
我正在通过另一个页面上的cookie传递团队名称。 当用户到达新页面时,我检查该团队名称是否在我的数组中存在,然后执行某些操作,如果不执行其他操作。 这很好。 但是,如果条件为真,我想将变量$ team_color设置为找到团队名称的嵌套数组中的颜色。
我不知道如何访问它。
我目前正在尝试访问array_values,但是没有运气。 任何建议将不胜感激。
这是我到目前为止所拥有的-
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'
)
);
if(in_array($team_cookie, array_column($team_info, 'team_name'))) {
$team_color = array_values($team_info, 'team_color');
// Do something
}
}
因此,要获取团队名称的团队颜色,您应该重组$team_info
数组,以便以键作为团队名称和值作为团队颜色的方式更快地进行访问。 我们首先使用array_column
检索所有team names
,然后为team_color
检索相同的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]
以获取团队颜色。
更新:
如果您的要求是仅搜索单个团队的颜色,则可以使用简单的foreach循环并检查team_cookie
与任何团队名称匹配,然后将其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;
}
检查以下代码,这将对您有所帮助。
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'
)
);
$find = check_inarray($team_cookie,$team_info);
if($find>0){
//If found do some action
}
function check_inarray($team_cookie,$team_info){
for($i=0;$i<count($team_info);$i++){
if($team_info[$i]['team_name']==$team_cookie)
return true;
}
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.