Removing an Array Object if key is found - php

How can I remove a whole array object if a $key=>value matches?
For example in my data I have ["endDate"]=> string(10) "2017-06-24" and if that date matches todays date('Y-m-d') I would like the whole object bock to be removed from the $row
Code:
foreach ($json->data as $row)
{
$date = date('Y-m-d');
if($row->endDate == $date){
$search = array_search($date, array_column('endDate', $row));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
JSON:
$response = $o->curl(sprintf($url, $propertyID, $pageSize, $pageNumber, $resultsFrom));
$json = json_decode($response);

$date = date('Y-m-d');
foreach ($json->data as $index=> $row){
if($row->endDate == $date) unset($json->data{$index});
}
foreach ($json->data as $row){
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
You may also consider just skipping to the next iteration, since it looks like you are building a guest email list and are not trying to modify the source of the json feed.
$date = date('Y-m-d');
foreach ($json->data as $row){
if($row->endDate == $date) {
continue;
}
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
Between the two options I pose, the second one requires less code and will yield slightly faster execution times.

If you place an ampersand before $row in your foreach you can change $json->data directly. From what you wrote, I think I understand your question and this may be what you need.
foreach ($json->data as &$row)
{
$date = date('Y-m-d');
if ($row->endDate == $date) {
$search = array_search($date, array_column('endDate', get_object_vars($row)));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
If not then rephrase your question so I might provide the answer you need.

Related

Insert data from excel (xlsm,xls) in laravel (cyber-duck)

Currently I can get the json data from my excel file with format like this
sample.xlsx
$excel = Importer::make('Excel');
$excel->hasHeader(true);
$excel->load($savePath.$fileName);
$collection = $excel->getCollection();
if(sizeof($collection[1]) == 5)
{
return $collection;
}
else
{
return redirect()
->back()
->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
->with('modal',$modal);
}
output
[{"id":1,"first_name":"j.doe17","last_name":"Jun Doe","email":"j.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}},{"id":2,"first_name":"j.doe18","last_name":"Jun Doe","email":"jan.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}}]
Now I'm trying to use this code, just insert those json data to my database table > tbl_sampleimport
foreach ($collection->toArray() as $key => $value) {
foreach ($value as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate'],
'created_at' => now(),
'updated_at' => now(),
);
}
}
DB::table('tbl_sampleimport')->insert($insert_data);
My Table tbl_sampleimport
But this gives me an error like this Illegal string offset 'first_name'
Laravel : v5.8.*
cyber-duck/laravel-excel
use json_decode() to convert into array
$arr = json_decode($collection, true);
foreach($arr as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate']['date'],
'created_at' => now(),
'updated_at' => now(),
);
}

PHP remove array if subarray empty

my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();
Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});
<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))

Access element in array(array(array(...)))

I am having the following array with test data:
'team' =>
array (
0 =>
array (
'firstName' => 'adfadsf',
'lastName' => 'asdfadsfa',
'twitter' => 'ddasfasdf',
),
1 =>
array (
'firstName' => 'adf',
'lastName' => 'asd',
'twitter' => 'www.twitter.com/dfs',
),
2 =>
array (
'firstName' => 'asd',
'lastName' => 'adf',
'twitter' => 'www.twitter.com/adf',
),
3 =>
array (
'firstName' => 'test',
'lastName' => 'test',
'twitter' => 'www.twitter.com/test',
),
),
I would like to access the attributes firstName and lastName.
I tried the following, where $request has as one attribute the team array:
foreach ($request as $key => $value) {
Log::info($key);
$team = new Team();
$team->firstname = $request->team[$key]['firstName'];
$team->lastname = $request->team[$key]['lastName'];
$team->twitter = $request->team[$key]['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}
Any suggestions how to access the two attributes firstName and lastName?
I appreciate your replies!
As it is not completely clear what's in $request, but I suggest this:
foreach ($request as $key => $value) {
Log::info($key);
if ($key == 'team') {
foreach ($value as $ar_team) {
$team = new Team();
$team->firstname = $ar_team['firstName'];
$team->lastname = $ar_team['lastName'];
$team->twitter = $ar_team['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}
}
}
Or simply (if other items in $request are not used in foreach):
foreach ($request['team'] as $ar_team) {
$team = new Team();
$team->firstname = $ar_team['firstName'];
$team->lastname = $ar_team['lastName'];
$team->twitter = $ar_team['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}
looking to your data sample
you should iterate over $request['team'] and accessing to $value for obtain firstName and lastname....
foreach ($request['team'] as $key => $value) {
Log::info($key);
$team = new Team();
$team->firstname = $value['firstName'];
$team->lastname = $value['lastName'];
$team->twitter = $value['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}

Number not increasing with each refresh of page

What I am trying to do every time the page is refreshed $insertedBookings should be adding how many were entered so that it becomes a total however its still staying at 6 there is a total of 11 items to be entered.
Code Updated:
$insertedBookings = 0;
foreach($json->data as $row)
{
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate)) == date('Y-m-d'))
{
$insertedBookings ++;
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
// Insert to IF HERE
if (!isset($_SESSION["totalInsertedBookings"]))
{
$_SESSION["totalInsertedBookings"] = $insertedBookings;
}
$currentInsertedBooking = $_SESSION["totalInsertedBookings"];
**Code:**
$insertedBookings = 0;
foreach($json->data as $row)
{
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate)) == date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
$insertedBookings = count($guests);
}
}
// Insert to IF HERE
if (!isset($_SESSION["totalInsertedBookings"]))
{
$_SESSION["totalInsertedBookings"] = $insertedBookings;
}
$currentInsertedBooking = $_SESSION["totalInsertedBookings"];
Because count($guests) is counting the number of elements in the $guests array which is 6 (FirstName, LastName, etc.).

Laravel - prepared statement contains too many placeholders

Im wondering if someone could give me a hand.
I have written an import script, it works fine for a small number of points, but when i start importing large numbers, i get the following error:
General error: 1390 Prepared statement contains too many placeholders
The code that im using to import is as follows:
foreach ( $items as $item ) {
$insert[] = array(
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
);
}
if(DB::table('mytable')->insert($insert))
{
return true;
} else {
return false;
}
Any help with figuring out how to fix this would be greatly appreciated.
function addData($items) {
$itemsTemp = [];
if (count > 1000) {
$itemsTemp = array_slice($items, 1000);
$items = array_slice($items, 0, 1000);
}
foreach ( $items as $item ) {
$insert[] = [
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
];
}
if (DB::table('mytable')->insert($insert)) {
if ($itemsTemp) {
addData($itemsTemp);
}
} else {
return false;
}
return true;
}

Categories