0

I need to make a DB inert which looks like this:

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0]
]);

But I am tryint to build the data with dynamic values eg in a loop add more times:

array_push($a,'email' => $this->mail,'votes' => $this->votes);

So that I can simply run this later:

DB::table('users')->insert($myData);

So how can I push a dimensional array?

1
  • What exactly are you looping? Can you show structure? Commented Nov 18, 2016 at 2:41

5 Answers 5

1

If I understand your question correctly .you can do simply do this , you can push you arrays to the original array so it will create a multidimentinal array.

    $a = array();
    array_push($a,array('email' => $this->mail,'votes' =>  $this->votes));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thats how I messed up, I forgot array(
0

You can do something like:

    $array = [];

    $dataComingFromSomewhere = [];   // Assuming this is your data source

    for($index = 0; $index < count($dataComingFromSomewhere); $index++)
    {
       $newUserArray = ['email' => $dataComingFromSomewhere[$index]->email, 'votes' => $dataComingFromSomewhere[$index]->votes];
       array_push($array, $newUserArray);
    }

    DB::table('users')->insert($array);

Comments

0

just this,

$myData[]= array('email' => $this->mail,'votes' => $this->votes);
DB::table('users')->insert($myData);

Comments

0

Improper use of array_push(). To push a single Associative Element it's like:

$a['email'] = $this->mail; $a['votes'] = $this->votes;

or do this:

$a = array_merge($a, array('email' => $this->mail, 'votes' => $this->votes));

Comments

0

First initialize $a as empty array $a = array()

Then change the line

array_push($a,'email' => $this->mail,'votes' => $this->votes);

to

array_push($a,array('email' => $this->mail,'votes' => $this->votes));

and you can do,

DB::table('users')->create($a);

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.