Home > database >  push data into object into array php
push data into object into array php

Time:10-19

Well, I have an array that contains objects inside.

it's something like this...

[{"name"=>"Pepe"},
 {"name"=>"Jane"},
 {"name"=>"Max"},
 {"name"=>"Mishelle"},
 {"name"=>"Petter"},
 {"name"=>"George"},
 {"name"=>"Maria"}]

What I'm trying to do is make a for loop and in each iteration insert, for example, a last name for each first name. The Array should be something like this...

[{"name"=>"Pepe",
  "last_name","smith"},
 {"name"=>"Jane",
  "last_name","jhonson"},
 {"name"=>"Max",
  "last_name","valdez"},
 {"name"=>"Mishelle",
  "last_name","smith"},
 {"name"=>"Petter",
  "last_name","planck"},
 {"name"=>"George",
  "last_name","smith"},
 {"name"=>"Maria",
  "last_name","kennedy"}]

This is make with PHP

$data = DB::table('guia_sucursal')
    ->join('colecciones','colecciones.id','=','guia_sucursal.coleccion_id')
    ->join('sucursales','colecciones.sucursal_destino_id','=','sucursales.id')
    ->select('colecciones.id as id','colecciones.titulo as titulo','colecciones.image as url','colecciones.codigo_barra as code_bar','sucursales.nombre as sucursal_destino')
    ->groupBy('guia_sucursal.coleccion_id')
    ->distinct('guia_sucursal.coleccion_id')
    ->get();

    foreach ($data as $coleccion){
        $num = 1;
        array_push($coleccion, "sucursal"=>"SUCURSAL".$num);

        $num = $num  1;
    }

CodePudding user response:

https://www.php.net/manual/en/control-structures.foreach.php

/* This is not valid php code, you copied it from var_dump or something,
    users = {"name"=>"Pepe"},
 {"name"=>"Jane"},
 {"name"=>"Max"},
 {"name"=>"Mishelle"},
 {"name"=>"Petter"},
 {"name"=>"George"},
 {"name"=>"Maria"}
]
*/

foreach($users as $user){
    $user->last_name = 'Last name of user';
}

But you haven't provided information about "last_name" data.

Do you have 2 arrays, one containing "name" and other containing "last_name"?

*** Edit** Question: "What I really need is to know how to add a new field and its respective value to an Object."

class User {
    public $name;
    public $last_name;
}

$user = new User;

$user->name = "Jake";
$user->last_name = "Li";

Since you are fetching data from database, adding data like this will not store it in database after script is finished.

Let's create array of objects like you have in example above

$users = [
    new User,
    new User,
];

Which is essentialy:

/* 
    $users = [
        {},
        {}
    ];
*/

Now we have $users array of 2 user objects.

To add properties to those users we simply like in above example use: ' -> '

foreach($users as $user){
    $user->name = 'Max';
    $user->last_name = 'Maxximus';
}

So every $user in array now has name='Max' and last_name='Maxximus'

  • Related