Change global 2d array from a function PHP? - php

$q = $_POST['q'];
$inCart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
function alreadyInCart() {
global $inCart, $good, $q;
foreach ($inCart as $inCart1) {
if ($inCart1[0] == $good->id) { // if this good already in cart
$inCart1[1] = $inCart1[1] + $q; // write sum of q's to existing array
return true; // and return true
}
}
return false; // return false if not
}
if (alreadyInCart() == false) { // if good added to cart for the first time
$inCart[] = array($good->id, $q); // add array at the end of array
}
Hello. So my problem is that I'm running a function to find out if $good->id is already inside of 2d $inCart array.
$inCart looks something like this:
Array
(
[0] => Array
(
[0] => 6
[1] => 1
)
[1] => Array
(
[0] => 5
[1] => 1
)
)
Where [0] is a good ID and [1] is an amount of this good in a cart.
So I tracked that function actually does what I want and returns true/false as expected, but looks like it only does it inside of itself. Cause if I put print_r($inCart1[1]) inside of a function it does add up and outputs the sum, as expected. But when I output the array at the end of the code (outside the function) the amount doesn't add up, just stays how it was before the function run.
Any ideas why that happens?

Ok, in case someone faces the same problem: found a solution.
Or should I say found a mistake?
The problem was with the foreach ($inCart as $inCart1). Must be replaced with foreach ($inCart as &$inCart1) in order to change array values in a loop. The other way, it just reads values, bit can't change them.

Related

PHP class to find value in array from session

I am trying to make a simple class that I can use to check if a value exists within an array. There is a session that contains multiple tool values. I am trying to pass the toolID to this function as well as a key and see if that value exists.
Session Data:
Array
(
[keyring] => Array
(
[tool] => Array
(
[toolID] => 1859
[keys] => Array
(
[0] => 49
[1] => 96
)
)
)
)
class Keyring
{
public function checkKey($key, $toolID){
$keyring = $_SESSION['keyring'];
if(isset($keyring)){
foreach($keyring['tool'] as $k => $v) {
if($k == 'toolID' && $v == $toolID){
if (in_array($key, $k->keys)){
return true;
}
}
}
}
return false;
}
}
$keyring = new Keyring();
print_r($keyring->checkKey(49, 1859));
In this example, I am trying to see if key 49 exists in the session for tool 1859.
I am getting the following error : Warning: in_array() expects parameter 2 to be array, null given in.
Is there a better approach for this? All I am looking for is a true/false as to whether that key exists in the keys array for the specified tool.
For my code to work for you may need to change your array a bit or change the code a bit, but rather then looping through a bunch of keys trying to find the right one we are just looking for the keys in the array if they are not set, then return false, or if we find keyring - tools - $tool_id - key_{$key_id} we are just going to return that value, if key_49 = false the function returns false. This should be a tad bit quicker to run on the server for you.
function has_keyring($tool_id, $key_id)
{
//Just to keep the code tidy let's store the tools key in $tool variable
$tool = $_SESSION['keyring']['tools'];
if(isset($tool[$tool_id]) && isset($tool[$tool_id]["key_{$key_id}"]))
return $tool[$tool_id]["key_{$key_id}"];
return false;
}

PHP - adding an object with its properties to array

I have a problem with modifying an array.
foreach ($page->getResults() as $lineItem) {
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
This code gives a result:
Array
(
[0] => Google\AdsApi\Dfp\v201611\Location Object
(
[id:protected] => 2250
[type:protected] => COUNTRY
[canonicalParentId:protected] =>
[displayName:protected] => France
)
)
I'm trying to add another, [1] , same type of object to this array.
I made a class to create and add an object:
class Location{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');
array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);
Then, if I pass this into print_r() function
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
It shows the same result.
In the end, I need to send this updated whole $lineItem to this function
$lineItems = $lineItemService->updateLineItems(array($lineItem));
But seems like before sending I can't properly add an object to the array.
Thanks in advance.
PHP returns arrays as a value instead of as a reference. This means you must set the modified value back somehow.
Looking at the library apparently in question, there seems to be setExcludedLocations method for that purpose.
So your code should be something like:
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);

How to call function inside controller inside foreach loop with different parameters value

i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.

(PHP) Trouble iterating through objects

Background: I am pulling in XML objects from a public IMDB-for-TV API. My goal is to pull certain values out of those objects -- like, say, a list of every episode title, put into an array so that I can do what I want with it.
Problem: Although I can write code that does execute exactly the way I want it, it spits out errors as it does so, so I know something's wrong with the way I iterate over my objects... but I can't figure out a better way. I'd really love some advice.
So first off, here's a look at the object I'm dealing with.
SimpleXMLElement Object
(
[Episodelist] => SimpleXMLElement Object
(
[Season] => Array
(
[0] => SimpleXMLElement Object
(
[episode] => Array
(
[0] => SimpleXMLElement Object
(
[epnum] => 1
[seasonnum] => 01
[prodnum] => 101
[airdate] => 1989-07-05
[link] => http://www.tvrage.com/Seinfeld/episodes/305788
[title] => Good News, Bad News
)
[1] => SimpleXMLElement Object
(
[epnum] => 2
[seasonnum] => 02
[prodnum] => 103
[airdate] => 1990-05-31
[link] => http://www.tvrage.com/Seinfeld/episodes/150618
[title] => The Stakeout
)
The show is an object containing an object "episode list", which contains object "season x", which contains object "episode y", which contains the value I'm after -- "title". So for each episode, I want to grab $this->list->Season[X]->episode[Y]->title.
Here is the function I wrote to do this. It takes two arguments: the season number, and the episode number.
public function showEpisode($s,$e) {
$s = $s - 1; // To compensate for zero-indexing.
$e = $e - 1;
if (!empty($this->list->Season[$s]) && !empty($this->list->Season[$s]->episode[$e])) {
return $this->list->Season[$s]->episode[$e]->title;
} else {
return 0;
}
}
I know there's something wrong with how it's written.
Anyway, here's my code for actually working with it.
$season = 1;
$episode = 1;
$errors = 0;
while ($errors < 2) {
if ($xfiles->showEpisode($season,$episode)!= 0) {
echo $xfiles->showEpisode($season,$episode) . "<br />";
$episode++;
$errors = 0;
} else {
$errors++;
$season++;
$episode = 1;
}
}
My logic is:
Start at Season 1, Episode 1.
Echo the title of the current episode.
If that fails, increment the error-counter by one, and go up a season by incrementing $season++ and putting the $episode counter back at 1.
If you get two errors in a row, it means going up a season failed, because we've hit the end of the show, so the loop ends.
Desired result: A neat, simple list of every episode title.
Actual result: A blank page, using this code; nothing is ever returned. When I used my last version of the function, which I have very stupidly deleted and cannot seem to recreate, I did echo a full set of episodes exactly as I wanted -- but after each season, and three times at the end of the file, I got "Trying to get property of non-object" errors, because of the calls to non-existent episodes.
Question: What is the correct, practical way to loop through a large object like this? What conditions should I use in my showEpisode function to check if the result will exist or not?
Thanks a ton to anyone who can help, I've done my best and Googled a lot but I'm just baffled.
This looks like a job for a foreach-loop.
foreach ($xfiles->list->Season as $season) {
foreach ($season->episode as $episode) {
echo $episode->title . "<br />";
}
}
Alternatively (or should I say ideally), put this inside a method of the list object and replace $xfiles with $this.

$query->result_array() wipes away list_fields() data

I'm having an issue where I call the result_array() function on n query object from in codeigniter:
$this->db->select(array('a','b','c'));
$query = $this->db->get('basic');
print_r($query->list_fields());
$test = $query->result_array();
print_r($query->list_fields());
When I run this code, or:
$query = $this->db->get('basic');
print_r($query->list_fields());
print_r($query->list_fields());
or:
$query = $this->db->get('basic');
$test = $query->result_array();
print_r($query->list_fields());
The second list_fields() function always returns an array size 0, the first returns the correct list of field names.
In the last example where there is only one list_fields() function, the array is again size zero.
Any guidance in this matter will be greatly appreciated. I need the list_fields() function to be accessible after I read the result_array().
Here is the result of the first block of code:
Array
(
[0] => site_id
[1] => institution
[2] => caller
[3] => call_complete
[4] => call_details
[5] => id
[6] => timestamp
)
Array
(
)
Thank you, for your help
That looks to be a bug in the database driver. For example, in CI_DB_mysqli_result:
public function list_fields()
{
$field_names = array();
while ($field = $this->result_id->fetch_field())
{
$field_names[] = $field->name;
}
return $field_names;
}
A subsequent call will return array() because the while loop seeks over all the fields and leaves the pointer at the end of the list.
However, in the result class, result_id is public, so you can use mysqli_result::field_seek:
$query = $this->db->get('basic');
var_dump($query->list_fields());
// this should be called before any call to list_fields()
$query->result_id->field_seek(0);
var_dump($query->list_fields());
However, this is bad practise, as this only works for mysqli; for mysql, you'll need this:
mysql_field_seek($query->result_id, 0);
and for mssql:
mssql_field_seek($query->result_id, 0);
The correct way to do this is really to fix it in the database drivers. See this pull request :-)

Categories