2

My current code is as follows

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..
}

But I want it to update it so that each line result have different (two) variable like as follows.

$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
3
  • What is $flowers? An array of Flower objects? Commented Oct 31, 2015 at 8:02
  • The variable of $flowers is only an array. Thank you! Commented Oct 31, 2015 at 8:07
  • I'm so sorry! $flowers is an Object and not an Array. Commented Oct 31, 2015 at 8:47

4 Answers 4

1

So if it's an array and not an object, you'd access keys like this:

$name = $flower['cust_name'];
Sign up to request clarification or add additional context in comments.

1 Comment

I'm sorry! the $flowers is not an Array, but its an Object
1

You are trying to show object data like -> symbol but $flower is an array so try the following

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

1 Comment

I'm so sorry I've updated with new comment of $flowers is an Object, not Array.
1

Like this

$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;          
}

1 Comment

Thank you, I'm working with it. Please patient for my feedback.
1

Using ${} is a way to create dynamic variables.So Try the following

<?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;        
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.