Laravel list() with each() function error with deprecated function - php

I get a little confuse here on how to alternatively replace the each() function since it was deprecated and I'm aware of that and fixed some of the while( list() = each() ) error case in my project. However, what other option should I use for this case:
foreach($new_id as $new_ids) {
list($key,$valueAddress) = each($address);
list($key,$valueCity) = each($city);
list($key,$valueState) = each($state);
if(isset($_POST['publicOnly'])) {
list($key,$valuePublicOnly) = each($publicOnly);
} else {
$valuePublicOnly = 0;
}
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = $valueAddress;
$propertyAddress->city = $valueCity;
$propertyAddress->state = $valueState;
$propertyAddress->publicOnly = $valuePublicOnly;
$propertyAddress->save();
}

You're not using the keys so just get the current value and then move to the next one:
foreach($new_id as $new_ids) {
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = current($address);
$propertyAddress->city = current($city);
$propertyAddress->state = current($state);
$propertyAddress->publicOnly = isset($_POST['publicOnly']) ? current($publicOnly) : 0;
$propertyAddress->save();
next($address); next($city); next($state); next($publicOnly);
}
However, if the keys are the same in all of the array then I think really this should work:
foreach($new_id as $key => $new_ids) {
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = $address[$key];
$propertyAddress->city = $city[$key];
$propertyAddress->state = $state[$key];
$propertyAddress->publicOnly = isset($_POST['publicOnly']) ? $publicOnly[$key] : 0;
$propertyAddress->save();
}

Related

PHP add unique User array to newly created array while iterating over Episode authors object

Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

Laravel conditional statement with each() result error

Partly confused (still) because the variable $investment_type resulting of "Creating default object from empty value" when I follow this previous question of mine Laravel list() with each() function error with deprecated function.
This is the original code.
$assetsData = ClientPropertyManagement::find($assets_id);
$investmentType = Input::get('investmenttype'.$assets_id);
$legalname = Input::get('legalname'.$assets_id);
$ownership = Input::get('ownership'.$assets_id);
$tic = Input::get('tic'.$assets_id);
$entity_id = Input::get('entity_id'.$assets_id);
foreach($investmentType as $investment_type) {
list($key,$value) = each($legalname);
list($key,$valueOwner) = each($ownership);
list($key,$valueTic) = each($tic);
list($key,$valueEntityId) = each($entity_id);
if($valueEntityId == 0) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($valueEntityId);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $value;
$assetEntity->ownership = $valueOwner;
$assetEntity->ticnum = $valueTic;
$assetEntity->save();
}
Here's what I did in my code.
foreach( $investmentType as $key => $investment_type ) {
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->save();
}
The problem is that $assetEntity isn't created yet, and you are trying to use as an object. To solve that, you need to change the position where you instantiate the object and create the variable $assetEntity:
foreach( $investmentType as $key => $investment_type ) {
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
$assetEntity->save();
}
That way $assetEntity will be created, and then you populate the other attributes.
Also, you may want to use the IoC Container and replace the new ClientEntityManagement with App::make('ClientEntityManagement'). Read more at https://laravel.com/docs/4.2/ioc

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

php while loop error

I have a PHP MySQL fetch while loop as shown below in my script:
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
}
In that I have a problem. I get the result as like below (JSON):
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"},{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
But I need the result as like below:
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
As you can see configurablepone JSON is getting repeated for every loop so I am getting the value of the first product in second product also but I need to seperate like below:
First Product As Like Below
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}]
Second Product As Like Below
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}]
I have tried changing the loop but I haven't found any solutions. Kindly help me to solve this.
I think, your problem in line $subpro1[] = substr($subpro, 0, -1)."}";.
So, first call of this line save data from "Veg.Pizaa" into $subpro1[0].
Second call of this line save data from "Core i7 Pc" into $subpro1[1].
Then, line $subproa = "[".implode(",",$subpro1)."]"; merged all array elements.
Just Use unset($subpro1); after the array_push($totArr, $prodObj2);.
Below Is An example Source
Try This One This May Work
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
unset($subpro1);
}
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
$subpro1 = array();
}
try this in second while loop

Categories