0

我对 php 很陌生。我有一个 foreach 循环

foreach ($sizes as $w => $h) {

echo 'index is '.$w.' and value is '.$h;}

我需要将这些值(我有 2 个值)分配给变量

$firstItem = foreach value 1

$secondItem = foreach value 2

我该怎么做谢谢

4

5 回答 5

2

使用 list() 函数作为

list($firstItem, $secondItem) = $sizes;
echo $firstItem , ' ', $secondItem;
于 2013-10-13T17:09:22.990 回答
1

我认为你应该这样做。

list($firstVariable,secondVariable) = $sizes;
于 2013-10-13T17:11:40.150 回答
1
foreach ($sizes as $w => $h) {

$firstItem = $sizes[$w1];
$secondItem = $sizes[$w2];
}

其中 $w1 是第一个键并且 $w2 是第二个键

于 2013-10-13T17:12:13.540 回答
0

根据 Tamil Selvan 的评论

<?php
$sizes = array("5","10");
list($firstItem, $secondItem) = $sizes;
echo $firstItem." - ".$secondItem;
?>

结果像

5 - 10
于 2013-10-13T17:11:00.623 回答
0

你可以试试这样的

//what is in "sizes"?
$sizes=array('a'=>'foo',
             'b'=>'bar');    

foreach ($sizes as $w => $h) {
${"item".$w}=$h;
}

echo "item a is ".$itema //item a is foo
echo "item b is ".$itemb //item b is bar
于 2013-10-13T17:13:48.983 回答