$codes = test1,test2,test3;
$names = 1226261693assistenza-pc-1-1.jpeg,1226261693cobinhood.png,1226261693a.png;
foreach($codes as $k=>$v AND $names as $k2=>$v2){
echo '<TR><TD>$k</TD><TD>$v</TD><TD>$k2</TD><TD>$v2</TD></TR>;
}
This method didn't work for me. Any suggestions?
This method didn't work for me. Any suggestions?
Cause
Missed quotes -
$codes = test1,test2,test3;
$names = 1226261693assistenza-pc-1-1.jpeg,1226261693cobinhood.png,1226261693a.png;
Should be like this
$my_string_var = '<your string>'; OR
$my_string_var = "<your string>";
That is not valid - foreach($codes as $k=>$v AND $names as $k2=>$v2){ }
foreach operates on only one array at a time.
Solution
If you have string variable like below,
$codes = 'test1,test2,test3';
$names = '1226261693assistenza-pc-1-1.jpeg,1226261693cobinhood.png,1226261693a.png';
Then make array and combine using array_combine(), them and then loop it like below
$array = array_combine ( explode(',',$codes), explode(',', $names) );
/*
loop array as array_key => array_value
$k = your array key
$v = you array value
*/
foreach($array as $k=>$v)
{
echo "<TR><TD>$k</TD><TD>$v</TD></TR>";
}
Or else define array itself like below and loop it
$array = array(
/* array_key => array_value */
'test1' => '1226261693assistenza-pc-1-1.jpeg',
'test2' => '1226261693cobinhood.png'
);
Related
ErrorException
Array to string conversion
$presocio = new Presocio;
$presocio->prestamo_id = $request->prestamo_id;
$presocio->ncuota = $request->ncuota;
$presocio->montopag = $request->montopag;
$presocio->fechapag = $request->fechapag;
$presocio->save();
In the end I managed to make it work like this, it works perfectly.
it can be done in different ways, example with ::create ::insert
$prestamo = new Prestamo;
$prestamo->socio_id = $request->socio_id;
$prestamo->monto = $request->monto;
$prestamo->cuotas = $request->cuotas;
$prestamo->alias = $request->alias;
$prestamo->save();
$idprestamo = $prestamo->id;
if (count($request->ncuota) > 0) {
foreach ($request->ncuota as $item => $v) {
$presocio = new Presocio;
$presocio->fill(
array(
'prestamo_id' => $idprestamo,
'ncuota' => $request->ncuota[$item],
'montopag' => $request->montopag[$item],
'fechapag' => $request->fechapag[$item],
)
);
$presocio->save();
}
}
toast('Pago Programados Registrado', 'success');
return redirect('prestamo');
Update since we now have the form supplied. You are using form names such as ncuota[] instead of ncuota which makes it an array. Are you able to make more than 1 Preseocio? if this is the case you want to loop over the items in the controller.
for ($i = 0; $i < count($request->ncuota); $i++)
{
Presocio::create([
'prestamo_id' => $request->prestamo_id[$i],
'ncuota' => $request->ncuota[$i],
'montopag' => $request->montopag[$i],
'fechapag' => $request->fechapag[$i],
]);
}
Otherwise just remove the [] off the end of the form names.
class Presocio
{
...
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'prestamo_id',
'ncuota',
'montopag',
'fechapag',
];
...
}
Presocio::create($request->all());
Now, Thats not the issue. That is just a bit of house keeping.
Your issue is that one of your request fields is an Array. Which ever one it is you will need to convert it to a JSON object or find a better way of storing it.
If you dont care and want to keep it as an array, modify the database field to be a jsonb field.
Try This create method
remove your all code and write only this code in your store method
$input = $request->all();
Presocio::create($input);
You can do that like:
for($i=0; $i < count($request->input('prestamo_id', 'ncuota', 'montopag', 'fechapag')); $i++) {
$presocio = new Presocio;
$presocio->prestamo_id = $request->prestamo_id[$i];
$presocio->ncuota = $request->ncuota[$i];
$presocio->montopag = $request->montopag[$i];
$presocio->fechapag = $request->fechapag[$i];
$presocio->save();
}
I am using laravel 5.6
My script to insert big data is like this :
...
$insert_data = [];
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$data = [
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
];
$insert_data[] = $data;
}
\DB::table('items_details')->insert($insert_data);
I have tried to insert 100 record with the script, it works. It successfully insert data
But if I try to insert 50000 record with the script, it becomes very slow. I've waited about 10 minutes and it did not work. There exist error like this :
504 Gateway Time-out
How can I solve this problem?
As it was stated, chunks won't really help you in this case if it is a time execution problem. I think that bulk insert you are trying to use cannot handle that amount of data , so I see 2 options:
1 - Reorganise your code to properly use chunks, this will look something like this:
$insert_data = [];
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$data = [
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
];
$insert_data[] = $data;
}
$insert_data = collect($insert_data); // Make a collection to use the chunk method
// it will chunk the dataset in smaller collections containing 500 values each.
// Play with the value to get best result
$chunks = $insert_data->chunk(500);
foreach ($chunks as $chunk)
{
\DB::table('items_details')->insert($chunk->toArray());
}
This way your bulk insert will contain less data, and be able to process it in a rather quick way.
2 - In case your host supports runtime overloads, you can add a directive right before the code starts to execute :
ini_set('max_execution_time', 120 ) ; // time in seconds
$insert_data = [];
foreach ($json['value'] as $value)
{
...
}
To read more go to the official docs
It makes no sense to use an array and then convert it to a collection.
We can get rid of arrays.
$insert_data = collect();
foreach ($json['value'] as $value) {
$posting_date = Carbon::parse($value['Posting_Date']);
$posting_date = $posting_date->format('Y-m-d');
$insert_data->push([
'item_no' => $value['Item_No'],
'entry_no' => $value['Entry_No'],
'document_no' => $value['Document_No'],
'posting_date' => $posting_date,
....
]);
}
foreach ($insert_data->chunk(500) as $chunk)
{
\DB::table('items_details')->insert($chunk->toArray());
}
Here is very good and very Fast Insert data solution
$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
$test_data[$i]['number'] = "1234567890";
$test_data[$i]['message'] = "Test Data";
$test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
foreach ($chunk_data as $chunk_data_val) {
DB::table('messages')->insert($chunk_data_val);
}
}
I used the code below to check the update or insert data of 11 thousand rows. I hope it useful for you.
$insert_data = [];
for ($i=0; $i < 11000; $i++) {
$data = [
'id' =>'user_'.$i,
'fullname' => 'Pixs Nguyen',
'username' => 'abc#gmail.com',
'timestamp' => '2020-03-23 08:12:00',
];
$insert_data[] = $data;
}
$insert_data = collect($insert_data); // Make a collection to use the chunk method
// it will chunk the dataset in smaller collections containing 500 values each.
// Play with the value to get best result
$accounts = $insert_data->chunk(500);
// In the case of updating or inserting you will take about 35 seconds to execute the code below
for ($i=0; $i < count($accounts); $i++) {
foreach ($accounts[$i] as $key => $account)
{
DB::table('yourTable')->updateOrInsert(['id'=>$account['id']],$account);
}
}
// In the case of inserting you only take about 0.35 seconds to execute the code below
foreach ($accounts as $key => $account)
{
DB::table('yourTable')->insert($account->toArray());
}
I use the following code to get data from two related tables:
$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;
$subcategories = $objectModel::with("translate", "parent")->get();
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
array_unshift($arr, 'Select category');
return $arr;
In result this part of code I get array with key => value to insert this in select list in Blade template.
But I desire to escape a loop:
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
And get clear collection from request. How can I do it?
You can use Laravel Collections https://laravel.com/docs/5.3/collections
$arr = ProductCategory::with("translate", "parent")->get()
->mapWithKeys(function ($item, $key) {
return [$item->translate()->first()->objectId => $item->translate()->first()->name];
})
->all();
I need to move outside a loop the $model->save() sentence, by example:
foreach ($nodes as $i => $node) {
$model = new Singer();
$model->name = $node['name'];
$model->birthDate = $node['birthDate'];
$model->save();
}
There is no way to save the model outside the loop? I mean if there is 100000 records in $nodes the save method will be executed 100000 times??
Thank you!
$values = array();
foreach ($nodes as $node) {
$values[]=array(
'name' => $node['name'],
'birthDate' => $node['birthDate']
);
}
Yii::app()->db->schema->getCommandBuilder()->createMultipleInsertCommand(Singer::model()->tableName(), $values)->execute();
There isn't any other solution. If you have 100,000 records, you have to iterate 100,00 times!
You can also use CDbCommand for faster response in this way:
$values = "";
foreach ($nodes as $i => $node) {
$values.= "(". $node['name'] . "," . $node['birthDate'] . ")" . ",";
}
$values = rtrim($values, ",") //remove last "," from $values
$sql = 'ISERT INTO "singer"(name, birthDate) VALUES '.$values;
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
I'm trying to save a lot of CActiveRecord model objects in a loop.
I have something like this:
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$object->save();
}
In my case, this creates about 400 CActiveRecord objects. The saving process is really slow, because each save() queries the database.
Is there a way to save all those objects in one go?
Something like:
$objects = array();
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$objects[] = $object;
}
save_all_objects($objects);
I could not find anything on the subject. Anyone?
you can validate() your model, and if it was ok you can append it so a sql text for insert,
and after your loop, just use databases commandBuilder() and execute your prepared text
$sql = '';
if($object->validate())
{
$sql .= ',("' . $object->attr1 . '")'// append to script,(you get the idea, you need to also make a correct values)
}
...
if(!empty($sql))
{
$sql = 'INSERT INTO table (attr1) Values' . $sql;// make complete script
// execute that command
}
Since v1.1.14, the method createMultipleInsertCommand() of CDbCommandBuilder class is available.
For insert multi rows, Put this code in components folder under GeneralRepository.php file name.
<?php
class GeneralRepository
{
/**
* Creates and executes an INSERT SQL statement for several rows.
* By: Nabi K.A.Z. <www.nabi.ir>
* Version: 0.1.0
* License: BSD3
*
* Usage:
* $rows = array(
* array('id' => 1, 'name' => 'John'),
* array('id' => 2, 'name' => 'Mark')
* );
* GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
*
* #param string $table the table that new rows will be inserted into.
* #param array $array_columns the array of column datas array(array(name=>value,...),...) to be inserted into the table.
* #return integer number of rows affected by the execution.
*/
public static function insertSeveral($table, $array_columns)
{
$connection = Yii::app()->db;
$sql = '';
$params = array();
$i = 0;
foreach ($array_columns as $columns) {
$names = array();
$placeholders = array();
foreach ($columns as $name => $value) {
if (!$i) {
$names[] = $connection->quoteColumnName($name);
}
if ($value instanceof CDbExpression) {
$placeholders[] = $value->expression;
foreach ($value->params as $n => $v)
$params[$n] = $v;
} else {
$placeholders[] = ':' . $name . $i;
$params[':' . $name . $i] = $value;
}
}
if (!$i) {
$sql = 'INSERT INTO ' . $connection->quoteTableName($table)
. ' (' . implode(', ', $names) . ') VALUES ('
. implode(', ', $placeholders) . ')';
} else {
$sql .= ',(' . implode(', ', $placeholders) . ')';
}
$i++;
}
$command = Yii::app()->db->createCommand($sql);
return $command->execute($params);
}
}
And usage anywhere:
$rows = array(
array('id' => 1, 'name' => 'John'),
array('id' => 2, 'name' => 'Mark')
);
GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
https://www.yiiframework.com/extension/yii-insert-multi-rows