I've got something but still it isn't working like I want it to work.
I've got an array
$values = array(
$aV=>$aP,
$bV=>$bP,
$cV=>$cP,
$dV=>$dP
);
then I sort
it like this ` arsort($values);
the result is Array ( [geel] => 28 [groen] => 20 [rood] => 20 [blauw] => 12 )
Now I want to acces the first / second / tird / fourth element to pass it on
So I want $values[0]
to be the first element. In this case Geel 28
. But if I try to echo $values[0]
it says Undefined offset: 0
(same with 1/2/3 etc). Obviously because I've got no [0]
set but how can I set [0]
to the first element in the array (which is different each time. the value geel
isn't always [0]
but I need the first element (with the lowest number) to be [0]
so I can echo $values[0]
to be the first element of the array with the lowest number
答案 0 :(得分:1)
如果您需要访问索引和数组的值,那么foreach循环可以为您做到这一点
$values = array($aV=>$aP, $bV=>$bP, $cV=>$cP, $dV=>$dP );
foreach ( $values as $idx => $val ) {
echo "Index is $idx and value is $val";
}
使用此数组作为示例
Array ( [geel] => 28 [groen] => 20 [rood] => 20 [blauw] => 12 )
输出将是
Index is geel and value is 28
Index is groen and value is 20
Index is rood and value is 20
Index is blauw and value is 12
答案 1 :(得分:0)
因为数组键已设置为geel,groen ..您无法访问$ values [0],$ values [1]。
您必须访问:
第一个元素:$values['geel']
第二个要素:$values['groen']
等......
答案 2 :(得分:0)
要将值和键作为数字索引访问,您需要使用array_values
和array_keys
<强>阵列:强>
$values = array(
$aV=>$aP,
$bV=>$bP,
$cV=>$cP,
$dV=>$dP
);
对于值:
$new_values = array_values($values);
结果:
array($aP, $bP, $cP, $dP);
对于键:
$keys = array_keys($values);
结果:
array($aV, $bV, $cV, $dV);
现在,您可以将数组作为数字键访问,例如:$keys[0]
或$new_values[0]
,依此类推。
答案 3 :(得分:-1)
不要使用&#34;箭头&#34;制作阵列的指标,您可能希望这样做:
$values = array(
$aV . ' ' . $aP,
$bV . ' ' . $bP,
$cV . ' ' . $cP,
$dV . ' ' . $dP,
);
您目前正在做的是创建一个看起来像这样的数组
[
'Geel' => 28
// etc.
]
如果您真的想获得第一个元素的值,可以使用array_shift