Unset Not Clearing Array Key/Value - php

I have form submission that redirects based on the results of a survey. On the landing page, I call a function to process query string, query the database and return results as an array for in-page processing.
function surveyResults() {
if($goodtogo) {
$survey = $wpdb->get_results(...,ARRAY_A);
$name_has_space = strpos(trim($q_name_field[0]),' ');
if($name_has_space === false) {
$q_first_name = $q_name_field[0];
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
} else {
$q_first_name = substr(trim($q_name_field[0]),0,$name_has_space);
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
}
$survey['name']['q_fname'] = $q_first_name;
$results = $survey;
} else {
$results = false;
}
return $results;
}
Output:
Array (
[0]=> Array (
'key' => 'value'
)
...
[n]=> Array (
'key' => 'value'
)
['name'] => Array (
[q_fname] => MyName
)
)
Which is perfect – except – each time I test the page, the $survey[0-n] results change as queried, but the $survey['name']['q_fname'] still holds the previous value MyName.
I have tried adding unset($survey['name']['q_fname']); immediately after setting $results = $survey; but that doesn't seem to make a difference. Do I need to unset($results) or use a reference &$fname...
What am I missing here?
Thanks

I'm macgregor, and I'm an idiot. Missed a critical piece of condition in the query.

Related

Why is there not enough memory in the simplest loop and with an array of 3 elements?

There is a function that displays categories ranging from the very top:
function getFullCategoryName($strCategoryId, $arrCategories)
{
$strCategoryIdPaent = NULL;
$arrCategoryCurr = isset($arrCategories[$strCategoryId]) ? $arrCategories[$strCategoryId] : NULL;
$arrCategoriesNames = [];
while (is_array($arrCategoryCurr)) {
$arrCategoriesNames[] = $arrCategoryCurr['title'];
if ($arrCategoryCurr['parentId'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
$arrCategoryCurr = $arrCategories[$arrCategoryCurr['parentId']];
} else {
$arrCategoryCurr = NULL;
}
}
krsort($arrCategoriesNames);
return implode(' > ', $arrCategoriesNames);
}
With just 3 array elements, I get an error:
"Allowed memory size of 134217728 bytes exhausted"
I understand that I am using something wrong. Please, help me understand what exactly.
This is my input array:
$arrCategories = array (
193450 =>
array (
'id' => '193450',
'parentId' => '193450',
'title' => 'Blood glucose meter',
),
193451 =>
array (
'id' => '193451',
'parentId' => '193450',
'title' => 'Sugar test strips',
),
193452 =>
array (
'id' => '193452',
'parentId' => '193452',
'title' => 'Blood glucose meter',
),
);
This is the call to the function:
$strCategoryId = 193450;
getFullCategoryName($strCategoryId, $arrCategories);
The while (is_array($arrCategoryCurr)) loop never ends as the else block of $arrCategoryCurr = NULL; is never called.
This happens because you have a loop where a node id is the same as his parent id. Look at your array:
....
'id' => '193450',
'parentId' => '193450',
...
To fix it modify the if statement to:
if ($arrCategoryCurr['parentId'] && $arrCategoryCurr['parentId'] != $arrCategoryCurr['id'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
Your (sample) data has an issue based on my reading of your function.
The parentId and index are the same in some items. This would create an infinite loop based on what I can work out from the question.
A better structure would be something like the following, with some error checking in the loop:
function getFullCategoryName($strCategoryId, $arrCategories) {
// set a base / default value
$arrCategoriesNames = [];
// do we even have anything to work with?
if (isset($arrCategories[$strCategoryId])) {
// at least one entry
do {
// get the title
$arrCategoriesNames[] = $arrCategories[$strCategoryId]['title'];
// get the next id and error check the data
if ((isset($arrCategories[$strCategoryId]['parentId'])) &&
($strCategoryId != $arrCategories[$strCategoryId]['parentId'])) {
// next index found and not the same
$strCategoryId = $arrCategories[$strCategoryId]['parentId'];
} else {
// either no parentId or a parentId that matches the current
// index. If that is the case, go no further.
$strCategoryId = false;
}
// you could add another error check if you like.
// if (count($arrCategoriesNames) == count($arrCategories)) {
// // go no further as data has a loop
// $strCategoryId = false;
// }
} while($strCategoryId);
// sort the data? why?
krsort($arrCategoriesNames);
}
// return a string
return implode(' > ', $arrCategoriesNames);
}
And testing you sample array;
$result = getFullCategoryName(193450,$arrCategories);
var_dump($result);
Returns the following:
string(19) "Blood glucose meter"

update checkbox value in CodeIgniter

I have an update query problem in CodeIgniter. I am trying to solve that problem but I can't. I have one array $arrpartnerId=([0=>1,[1]=>4,[3]=>5 like..) and my other array is $promotionData['promotion_id']. The inserting into checkbox value is correct, but the updating checkbox value is not working.
My model function is:
public function update_promotion($promotionData, $partnerData) {
// print_r( $promotionData['promotion_id']);
$arrPartnerId = $partnerData['partner_id'];
print_r($partnerData['partner_id']);
if (is_array($arrPartnerId) > 0) {
foreach ($arrPartnerId as $partnerId) {
$this->db->set('promotion_id', $promotionData['promotion_id']);
$this->db->where('partner_id', $partnerId);
$this->db->update('partner_promotion_relation');
}
}
}
If your array is like this,
$arrPartnerId = array(
0 => 1,
1 => 4,
2 => 5
);
And
$promotionData['promotion_id'] = 123; //assumption
Then try this,
if(sizeof($arrPartnerId) > 0 )
{
foreach( $arrPartnerId as $partnerId)
{
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
It will resolve the problem.

get data from array in cakephp

I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?
public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.

Find out if the price was zero when looking through php array of price history/changes

I have all the price changes in a array like this (date, pricechange). It is always in date order:
$pricehistory = array (
'2013-11-04' => 10,
'2013-11-10' => 0,
'2013-12-01' => 10
);
What I need is to find out if the price for a specific date was zero.
function was_free($date) {
// return boolean
}
was_free('2013-11-11'); //should return true;
was_free('2013-12-01'); //should return false;
Can someone please help me figuring out how to do this? I think I need to loop through the $pricehistory array backwards, but I'm not sure how to do it.
//$default - returned if price is not exits
function was_free($price_history, $current_date, $default = FALSE) {
if(isset($price_history[$current_date]))
{
return empty($price_history[$current_date]);
}
$current_timestamp = strtotime($current_date);
$history_timestamp = array();
foreach ($price_history as $date => $price)
{
$history_timestamp[strtotime($date)] = $price;
}
$history_timestamp[$current_timestamp] = NULL;
ksort($history_timestamp);
$previous_price = ($default) ? FALSE : TRUE;
foreach ($history_timestamp as $timestamp => $price)
{
if($timestamp == $current_timestamp)
{
break;
}
$previous_price = $price;
}
return empty($previous_price);
}
$price_history = array (
'2013-11-04' => 10,
'2013-11-10' => 0,
'2013-12-01' => 10
);
// run !!
var_dump(was_free($price_history, '2013-11-03'));
var_dump(was_free($price_history, '2013-11-04'));
var_dump(was_free($price_history, '2013-11-09'));
var_dump(was_free($price_history, '2013-11-10'));
var_dump(was_free($price_history, '2013-11-11'));
var_dump(was_free($price_history, '2013-12-01'));
var_dump(was_free($price_history, '2013-12-02'));
Try:
function was_free($date) {
return array_key_exists($date,$pricehistory) && $pricehistory[$date] === 0;
}
Since the $pricehistory isn't in the scope of the function, you may pass it as a parameter or access it using global.

jQuery Auto Complete Return Data - Showing the ID aswell as label

I am using Codeigniter to create an Autocomplete for user names:
Using the parameter : search-user?term=s I get the following data back as Json :
{"id":"1","value":"Stuart Blackett"}{"id":"2","value":"Simon Wilton"}
However when I am running the auto select, On the search for say "St" it brings back by name in the options, But also the ID as well.
How do I prevent this from happening? I suspect my loop could be the issue.
My PHP Function is as follows :
function search_user()
{
$term = $this->input->get('term');
$user_search = $this->vendor_model->search_user($term);
$user['response'] = 'false';
if(count($user_search) > 0)
{
$user['response'] = 'true';
$user = array();
foreach($user_search as $user)
{
$user = array(
'id' => $user->user_id,
'value' => $user->user_firstname .' '. $user->user_surname
);
echo json_encode($user);
}
}
}
{"id":"1","value":"Stuart Blackett"}{"id":"2","value":"Simon Wilton"} isn't valid JSON.
Try not echoing each $user's information separately - instead, build a new array of users and json_encode() that array. Example:
foreach($user_search as $user) {
$users[] = array(
'id' => $user->user_id,
'value' => $user->user_firstname .' '. $user->user_surname
);
}
echo json_encode($users);

Categories