0

How to extract array values, then creating another arrays with the one of the items is taken from the value.

I have the the following code below.

Base code below:

$order_id = 325;
$fruits = ["Apple","Blueberry","Coconut"];
$date_created = date("Y-m-d H:i:s");

Then create new arrays like these below:

// These $var should be incrementing depends the $fruits values. (e.g: $var1, $var2, $var3, $var4 and so on..)
$var1 = [
        "order_id" => 325,
        "fruit_name" => "Apple",
        "date_created" => $date_created
        ];

$var2 = [
        "order_id" => 325,
        "fruit_name" => "Blueberry",
        "date_created" => $date_created
        ];

$var3 = [
        "order_id" => 325,
        "fruit_name" => "Coconut",
        "date_created" => $date_created
        ];

Result must be like below:

// The Result I wondering should be like this:
$array = [
        $var1,
        $var2,
        $var3,
        // $var4 if any..
        ];

Thank you for your help in advanced.

2 Answers 2

1

Use a foreach loop:

$array = array();
foreach ($fruits as $f) {
    $array[] = array(
        "order_id" => $order_id,
        "fruit_name" => $f,
        "date_created" => $date_created
    );
}

There should be no need for $var1, $var2, etc. Just push the new elements directly onto the array.

Sign up to request clarification or add additional context in comments.

Comments

0

as your said These $var should be incrementing depends the $fruits values ,so I made a little code by variable increment.

<?php
 $order_id = 325;
 $fruits = ["Apple","Blueberry","Coconut"];
 $date_created = date("Y-m-d H:i:s");
 $array = array();
  foreach ($fruits as $key => $value) {
    ${"var{$key}"} = array();//will get $var0,$var1,....etc
    ${"var{$key}"}["order_id"] = $order_id;
    ${"var{$key}"}["fruit_name"] = $value;
    ${"var{$key}"}["date_create()"] = $date_created;
 }    
 $array = [$var0,$var1,$var2];
 var_dump($array);

2 Comments

Please don't encourage the use of variable variables. There's practically never a use for them.
yes , I know it ,I just give the hint that he asked ! But Thanks for your comment.

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.