PHP 获取关联数组的第一个和第四个值


PHP get first and forth value of an associative array

我有一个关联数组,$teams_name_points .数组的长度未知。

如何在不知道此数组键的情况下以最简单的方式访问第一个和第四个值?

数组填充如下:

$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;

等。

我想做一些类似于索引数组的事情:

for($x=0; $x<count($teams_name_points); $x++){
    echo $teams_name_points[$x];
}

我该怎么做?

使用array_keys?

$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
您可以使用

array_values它将为您提供一个数字索引数组。

$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]

除了 array_values 之外,还要循环播放,如下所示:

foreach($teams_name_points as $key => $value) {
    echo "$key = $value";
}
您可以使用

array_keys函数,例如

//Get all array keys in array
$keys = array_keys($teams_name_points);

//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];

您现在可以按存在的方式获取所有值

$cnt = count($keys);
if($cnt>0)
{
     for($i=0;$i<$cnt;$i++)
     {
          //Get the value
          $value = $team_name_points[$keys[$i]];
     }
}