I'm unable to get the following code to work, and it has something to do with the forming of the array. The array is actually build after a foreach() loop runs a few times, then I want to batch insert, but it comes up malformed. Why?
foreach ($results as $r) {
$insert_array = array(
'ListingRid' => $r['ListingRid'],
'StreetNumber' => $r['StreetNumber'],
'StreetName' => $r['StreetName'],
'City' => $r['City'],
'State' => $r['State'],
'ZipCode' => $r['ZipCode'],
'PropertyType' => $r['PropertyType'],
'Bedrooms' => $r['Bedrooms'],
'Bathrooms' => $r['Bathrooms'],
'YearBuilt' => (2011 - $r['Age']),
'Status' => $r['Status'],
'PictureCount' => $r['PictureCount'],
'SchoolDistrict' => $r['SchoolDistrict'],
'ListedSince' => $r['EntryDate'],
'MarketingRemarks' => $r['MarketingRemarks'],
'PhotoUrl' => (!empty($photo_url) ? $photo_url : 'DEFAULT'),
'ListingAgentFirstName' => $r['ListingAgentFirstName'],
'ListingAgentLastName' => $r['ListingAgentLastName'],
'ContactPhoneAreaCode1' => (!empty($a['ContactPhoneAreaCode1']) ? $a['ContactPhoneAreaCode1'] : 'DEFAULT'),
'ContactPhoneNumber1' => (!empty($a['ContactPhoneNumber1']) ? $a['ContactPhoneNumber1'] : 'DEFAULT'),
'ListingOfficeName' => (!empty($r['ListingOfficeName']) ? $r['ListingOfficeName'] : 'DEFAULT'),
'OfficePhoneComplete' => (!empty($o['OfficePhoneComplete']) ? $o['OfficePhoneComplete'] : 'DEFAULT'),
'last_updated' => date('Y-m-d H:i:s')
);
$insert[] = $insert_array;
}
$this->db->insert_batch('listings', $insert);
Here's the errors:
A PHP Error was encountered
Severity: Warning
Message: array_keys() [function.array-keys]: The first argument should
be an array
Filename: database/DB_active_rec.php
Line Number: 1148
A PHP Error was encountered
Severity: Warning
Message: sort() expects parameter 1 to be array, null given
Filename: database/DB_active_rec.php
Line Number: 1149
Any ideas? Thanks!
I've reduced your code to the bare minimum and it seems to work.
$i = 0;
while ($i <= 10) {
$insert_array = array(
'code' => 'asd'
);
$insert[] = $insert_array;
$i++;
}
$this->db->insert_batch('group', $insert);
You should check the elements of the array, comment them all and de-comment them one by one until you got the culprit.
Looks like you need to wrap your array in a second array. You're supposed to provide an array of row arrays.
$insert_array = array(array(...));
Related
I've been reading around and cannot find a solution that works for the requirement I have. I need to dynamically add values to the 'add' part of this array depending on conditions. I know that you cannot put any if statements inside the array itself.
The correct syntax (from the documentation) is:
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
[
'inheritedFromId' => 'addon1',
'amount' => '10'
],
[
'inheritedFromId' => 'addon2',
'amount' => '10'
]
]
]
]);
From what I had read on a similar question on SO, I tried the following (where $addon1 and $addon2 would be the conditions set earlier in the code)
$addon1 = true;
$addon2 = true;
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
($addon1 ? array(
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
]) : false),
($addon2 ? array(
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
]) : false)
]
]
]);
But I get back a Warning: XMLWriter::startElement(): Invalid Element Name so I suspect that it does not like the structure and the code fails with a fatal error (interestingly, if I only set the first $addon to true it still comes up with the warning, but does actually work. With two it fails).
Is there another way to do this or did I get the syntax wrong?
I cannot hardcode all the possibilities due to the amount of possible product combinations.
Would appreciate and help. Thank you.
Don't try to do everything at once.
$add = [];
if( $addon1)
$add[] = ['inheritedFromId'=>.......];
if( $addon2)
.....
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => $add
]
]);
you can put if statements in array declarations, it's called ternary operations:
$myArray['key'] = ($foo == 'bar' ? 1 : 2);
this is the basis of how to use.
You're using the array() syntax together with the short array syntax ([]). See the manual. This means that e.g. your first element in add would be an array within an array. Perhaps that's why the XML error is occurring? Better would be:
'add' => [
($addon1 ?
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
] : null),
($addon2 ?
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
] : null)
]
]
Your syntax is fine. you are creating array with this structure
array (size=3)
'paymentMethodToken' => string 'the_token'
(length=9)
'planId' => string 'thePlanId'
(length=9)
'addOns' =>
array (size=1)
'add' =>
array (size=2)
0 =>
array (size=1)
...
1 =>
array (size=1)
...
My quess is that $gateway->subscription()->create() is does not like this structure of your array. Maybe the 'false' as value or the numeric keys. Check what does it expect and try again with new structure of the array.
I have the following code :
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$serviceVaccination = \App\UserServiceVaccination::updateOrCreate([
'user_service_id' => $id,
'vaccine_id' => $vaccine
],[
'specie' => 'Dog',
'user_service_id' => $id,
'vaccine_id' => $vaccine,
'duration_6' => $request->dog_duration_6[$key],
'duration_12' => $request->dog_duration_12[$key],
'duration_36' => $request->dog_duration_36[$key]
]);
}
Now the data coming along from the form is :
It gives me exception :
Undefined offset: 2
The request dog_duration_6, dog_duration_12, dog_duration_36 arrays can be different in terms of element size,
How can i pass null to avoid exception Undefined offset: 2 ?
Simply add a check like to avoid offset exception.:
isset($request->dog_duration_6[$key]) ? $request->dog_duration_6[$key] : null
For all of them.
'duration_6' => $request->dog_duration_6[$key] ?? null,
Here is my aggregation code for mongodb collection :
$mongo_db_name = "db_".$tenant_id;
$con = new MongoClient($this->config->item('mongo_instance'));
$db = $con->$mongo_db_name;
$collection = $db->$module;
$options = array('cursor' => array("batchSize" => 4 ));
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
$data = $collection->aggregate($pipeline,$options);
var_dump($data);
I am getting this error with the above code
array (size=4) 'ok' => float 0 'errmsg' => string 'Each element of
the 'pipeline' array must be an object' (length=54) 'code' => int 14
'codeName' => string 'TypeMismatch' (length=12)
If I try to encode the pipeline using json_encode the result is 'null'.
If I use find(array('deleted'=>'0')); it returns all documents as expected.
Can anyone help me about where I am going wrong or whatmust I do to resolve this ?
aggregation pipeline takes objects in array so your pipeline should be like
[
{$match:{}};
{$group:{}};
{$somepipelinestageOperator:{}}
]
but if you have pipeline with array as tages and not object you will get above error(each element of pipeline must be an array..).
[
[$match:{}],
[$group:{}],
[$somepipelinestageOperator:{}]
]
in your code there are array for match and group so its failing.
$pipeline=array(
array('$match'=>array('deleted'=>'0')),
array('$group'=>array('_id' => array('id'=>'$id', 'accountnm' => '$account_name', 'legal___corporate_name_cstm' => '$legal___corporate_name_cstm', 'funded_by_cstm' => '$funded_by_cstm', 'approval_amount_cstm' => '$approval_amount_cstm', 'payback_amount_cstm' => '$payback_amount_cstm', 'factor_rate_cstm' => '$factor_rate_cstm', 'daily_ach_amount__1_cstm' => '$daily_ach_amount__1_cstm', 'total_commission_owed_cstm' => '$total_commission_owed_cstm', 'total_commission_paid_cstm' => '$total_commission_paid_cstm', 'upfront_amount_due_cstm' => '$upfront_amount_due_cstm', 'upfront_amount_due_date_cstm' => '$upfront_amount_due_date_cstm', 'date_modified' => '$date_modified'))),
);
you can print your pipeline and see that your pipeline stages are having array and not object.
$aa = Input::get('AccountOpeningDate' . $i);
$dateinfo = explode("-", $aa);
$testDay = Carbon::createFromDate($dateinfo[0], $dateinfo[1],
$dateinfo[2], 'UTC');
$actualDate = $testDay->setTimezone('+6:00');
when I run this code then I get an output.But it cause an error that like the image below.
ErrorException in MemberController.php line 532:
Undefined offset: 1
in MemberController.php line 532
at HandleExceptions->handleError('8', 'Undefined offset: 1', 'C:\xampp\htdocs\timf\app\Http\Controllers\MemberController.php', '532', array('id' => '4001-5088-0565', 'memberdata' => object(Member), 'somityDay' => object(Zone1), 'i' => '2', 'aa' => '', 'dateinfo' => array(''), 'testDay' => object(Carbon), 'actualDate' => object(Carbon), 'producttype' => '2', 'memberaccount' => object(Accountstable), 'valsa' => object(Product), 'AccNameSub' => 'MSSM', 'accnumber' => 'MSSM.4001-5088-0565', 'k' => '13', 'SavingSetup' =>
This code is written in laravel 5.1.
$aa = Input::get('AccountOpeningDate' . $i);
Here $aa has no data in case of any conditions. So the array $dateinfo remaining empty. I have fixed the problem by ensuring $aa data not empty.
now the code is running well.
There may be a comma missing in your first line of code.
I'm trying to fetch all rows to an array variable
array that i want is like this
$data1 = array('fields'=>array(
array(
'id' => 1,
'nama_file' => "sunset.jpg",
'judul' => "Sunset",
'isi' => "Matahari terbenam indah sekali",
),
array(
'id' => 2,
'nama_file' => "water_lilies.jpg",
'judul' => "Bunga Lilly",
'isi' => "Bunga lilly air sangat indah",
),)
And I've done this:
$q = $this->db->query('select id, nama_file, judul, isi from tfoto where dihapus ="T" ');
$data1=array('fields');
foreach($q->result() as $row) {
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
}
test output:
<?php
foreach($fields as $field){
echo $field['nama_file'];
.
.
.
};?>
and I got Message: Illegal string offset 'nama_file';'judul'; etc.
I am a newbie to MySQL/PHP, so forgive me if this is a very basic question. I tried looking all over but I could not find an answer to it.
This line:
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Should be:
$data1['fields'][] = array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Because you have to append new arrays to $data1 and not replacing it.