在PHP中使用foreach循环为每个结果分配变量

时间:2015-10-31 07:58:50

标签: php variables foreach

我目前的代码如下

foreach($flowers as $flower){

        echo "Order by: " . $flower->cust_name . "with item: " . $flower->item;    

        // code result above
        // Order by: Anna Witck with item Lily
        // Order by: George Maxwel with item Rose
        // Order by: Catherine Giin with item Aster
        // and so on..
}

但是我希望它更新它,以便每行结果有不同的(两个)变量,如下所示。

$anna_cust = $flower->cust_name; // result: Anna Witck
$anna_item = $flower->item; // result: Lily
$george_cust = $flower->cust_name; // result: George Maxwel
$george_item = $flower->item; // result: Rose
$catherine_cust = $flower->cust_name; // result: Catherine Giin
$catherine_item = $flower->item; // result: Aster

4 个答案:

答案 0 :(得分:1)

因此,如果它是一个数组而不是一个对象,那么您可以访问这样的键:

$name = $flower['cust_name'];

答案 1 :(得分:1)

您正在尝试显示像->符号这样的对象数据,但$ flower是一个数组,请尝试以下

<?php
    foreach($flowers as $flower){
        echo "Order by: " . $flower['cust_name'] . "with item: " .$flower['item'];    
    }
?>

答案 2 :(得分:1)

喜欢这个

$data = array();
foreach ($flowers as $flower) {
    $name = explode(' ', trim($flower->cust_name));

    // Set varibale name
    $var_cust = strtolower($name[0]) . '_cust' ;
    $var_item = strtolower($name[0]) . '_item' ;

    $data[$var_cust] = $flower->cust_name;
    $data[$var_name] = $flower->item;          
}

答案 3 :(得分:1)

使用${}是一种创建动态变量的方法。请尝试以下

<?php
foreach($flowers as $flower){
        $cast_name = explode(' ', trim($flower->cust_name));
        ${strtolower($cast_name[0]). '_cust'}=$flower->cust_name;
        ${strtolower($cast_name[0]). '_item'}=$flower->item;        
}
?>