I am trying to insert some items (suppose n items), which are all different from each other, to an array. Somehow, the final array consists of n items, Which all are the same item: the last inserted item.
This is my code:
$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
$searchResultJSon->dealid = $searchResultItem['id'];
$searchResultJSon->title = $searchResultItem['title'];
//$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
//$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
$searchResults_data[] = $searchResultJSon;
}
So I tried to figure out why is that.. using DEBUGGING1,DEBUGGING2 (in the client side, I get the messages sent by $from->send() and simply alert() them).
When alerting the DEBUGGING1 messages - I do see that all the items are correct and different from each other.
When alerting the DEBUGGING2 messages - the array duplicates the last inserted item each loop. So assume I insert n items, The array in the i-th loop will be: [item-i, item-i, item-i, ... item-i] instead of [item-1, item-2, item-3,...,item-i]
Your problem is that you're not creating a new object each time you go through the loop, so when you push $searchResultJSon into $searchResults_data you are pushing the same object, and the changes you make to it in the last iteration of the loop are reflected in all the values in $searchResults_data. You can work around that by creating a new object in each pass:
$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
$searchResultJSon = new StdClass();
$searchResultJSon->dealid = $searchResultItem['id'];
$searchResultJSon->title = $searchResultItem['title'];
//$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
//$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
$searchResults_data[] = $searchResultJSon;
}
Related
I'm trying to create a function to fetch one or more random entries from my array but I'm having an "illegal call" array_rand error on my flow.
Then I realized that not all PHP functions are supported through GlobiFlow, so I was hoping that there's a workaround for this one.
screenshot:
Here are my variables:
choicesval = my array
randum = random number from 1 - 7
xField = random item(s) that were chosen from my array_rand
Here's the furthest that I got:
explode(",", choicesval)[intval(randum)]
But the problem is, it returns the element from my array based on the index. For example, my randnum got a value of 3, so in my Xfield, it will return the element at index 3 and not select 3 random items from my array.
Hope I'm making any sense at all.
I'm not successful in correcting my error above, however, I've found a workaround to achieve the same result.
I created a new var named limitnum = 0, then a for each loop:
for each item:
if limitnum <= randnum
choicesval = [(Ref Client) Company Name]. ", " .[(Variable) choicesval]
limitnum += 1;
end if
continue()
I'm attempting to make 1 array out of 2 existing arrays (which cannot be modified). In order to do this I'm creating the array in a foreach which is nested in another foreach.
The code I used:
$language_option = array();
foreach(Languages::getFullSelectOptionsList() as $country_description_1 => $country_code){
foreach(Languages::getFullSelectOptionsList(TRUE) as $country_description_2 => $country_code){
$language_option[$country_code] = $country_description_1.' - '.$country_description_2;
}
}
In this code "Languages::getFullSelectOptionsList()" returns an array with the 1st country descriptions.
And "Languages::getFullSelectOptionsList(TRUE)" returns an array with the 2nd country descriptions.
This is what my code does:
dropdown results
But what I'd like it to do is:
dropdown wished results
As you can see in the first picture only the last array value of "country_description_1" is used instead of using them all.
Are there any errors in my code, is this not possible to do or is there an easier way of doing this?
Thanks.
Here you can get reference of this code.
But This will not work because you need to specify the values where $first_array[$i]
$language_option = array();
$first_array = Languages::getFullSelectOptionsList();
$second_array = Languages::getFullSelectOptionsList(TRUE);
for($i=0;$i<count($first_array); $i++){
$language_option[$country_code] = $first_array[$i].' - '.$second_array[$i];
}
Instead of $first_array[$i].' - '.$second_array[$i] put code according to your array structure to get description or code (key value).
I'm using PHP to retrieve data from an SQL database to produce a stacked column chart in Highcharts. The idea is that I'm taking the following piece of code to retrieve values from my database. This code should generate an array which then gets encoded to JSON and passed to Highcharts; this code produces a single 'part' of a stacked column, and the index determines which vertical bar that part is in. (So in http://www.highcharts.com/demo/column-stacked, the index would represent which fruit, and the data in this series would represent one person/color.)
The issue is that when I run this code, instead of ending up with an indexed array of data grouped by category, such as
[12,13,14,15] where each item is a category, I end up with an associative array where the indexes I specified in the code are turned into a string key.
{"1":13,"0":12,"3":14, "2":13, "5":15}
Because my indexes are being interpreted as associative keys and not as the indexed locations of the data inside the array, the data is now being added to locations in the order that I retrieved the data, and not assigned to a location in the array based on the index I give. Highcharts assigns categories based on location in the array, and not on key, so all my data ends up in the wrong categories.
Is there a way to get PHP to treat my carefully collected indexes as indexes and not as keys, and add my data points in the location in the array indicated by the indexes? I'm kind of new to PHP, and Java and C++ - the languages I've worked with before - don't have associative arrays, so any help you can give me in explaining and fixing this undesired behavior would be much appreciated.
Code below.
$variable indicates what the data is being sorted into categories by, and $r is the variable representing the array of the SQL query, so $r['variable'] is the category of this data point, and $r['amount'] is the data point itself.
$found = -1;
//if this is the first set of data being collected
if (count($category['data']) == 0){
$category['data'][0] = $r[$variable];
$series1['data'][0] = floatval($r['amount']);
$count++;
$times1[0]++;
}
//if it's not the first set of data, find out if this category has been used before
else {
for ($x = 0; $x < count($category['data']); $x++){
if ($r[$variable] == $category['data'][$x]){
$found = $x;
break;
}
}
// if that category does not already exist, add it, and add the data
if ($found == -1) {
$times1[$count]++;
$category['data'][$count] = $r[$variable];
$series1['data'][$count] = floatval($r['amount']);
$count++;
}
else { //otherwise, add its data to the data already in the current category. This will eventually yield an average, with $times1[] as the divisor
$times1[$found]++;
$series3['data'][$found] = floatval((floatval($series3['data'][$found]) + floatval($r['amount'])));
}}
Go through with below code hope it will give some idea to resolve your problem --
<?php
$jsonstring = '{"1":13,"0":12,"3":14, "2":13, "5":15}';
$tempArr = json_decode($jsonstring, true);
asort(tempArr); // for sorting the array --
//run another foreach to get created an array --
$finArr = array();
foreach(tempArr as $key=>$val){
$finArr[] = $val;
}
$requiredjsonString = json_encode(finArr); // it will return your required json Array [12,13,14,15]
?>
Edit: I advice also set JSON_NUMERIC_CHECK flag in json_encode();
I am trying to build Dynamic UI by getting data from DB using CodeIgniter but facing problem in constructing array.
Requirement:
Get parent menu items in an array. Then get child item corresponding to each parent item.
Code to get data for parent element::
$data['menu'] = $this->Menu->get_admin_menu_data();
This gives me 3 records
echo "before loop menu" . count($data['menu']) . "</br>"; //prints 3
Now I run a foreach loop for each parent item to retrieve it's child item
foreach($data['menu'] as $menu){
$data['menu']['menu_item'] = $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
echo "inside loop menu " . count($data['menu']) . "</br>"; //prints 4
}
As soon as I do this the count of menu increases to 4 resulting in error in UI.
I am new to PHP so now sure what is the best way to create a structure to hold this type of data.
Please help!!!!
If $data['menu'] contains 3 key/value pairs, but $data['menu']['menu_item'] is not set, your statement
$data['menu']['menu_item']
= $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
sets just this.
Thus count( $data['menu'] ) returns 4 elements afterwards - including the newly added 'menu_item' key.
I don't know CodeIgniter, but overwriting a static variable
$data['menu']['menu_item'] = "someting"
never makes sense. Where do you really want to store the result of
$this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
? You can and should check the content of a variable using var_dump.
I'm new to web developing.
This is part of a phone service, and I'm trying to filter through 3 different arrays that are filled with strings from three database searches: $sfaa, $sfipc, and $sfuaa. I have to filter the three database arrays to locate available customer service agents. The output would be an array filled with the IVR_Number to dial.
Heres an example of the string: "'Id', 'IVR_Number', 'Market_Id'"
I have to explode the string in order to get my data from each value in the arrays. Then based on a one-to-many id in each string I have to check if the id from $sfaa is in $sfipc or $sfuaa. If not then I have to build an array with the filtered records, from there I have to locate a value from the exploded string in $sfaa that belongs to that id. I wrote the following code but theres got to be an easier way?? I hope.... The client has to wait for these results before moving forward. There is usually only 10 or 15 records.
This code works I'm just wondering if there is an easier way to do this
Any tips
// formalua needed to filter above results and fill $aadl array
// explode each active agent array
$activeagentsfec=0;
$aaivra= array();
$aaida= array();
foreach ($sfaa as $aavalue)
{
${'aadetails'.$activeagentsfec} = explode("'",$aavalue);
${'aaivr'.$activeagentsfec} = ${'aadetails'.$activeagentsfec}[5];
${'aaid'.$activeagentsfec} = ${'aadetails'.$activeagentsfec}[1];
array_push($aaivra, ${'aaivr'.$activeagentsfec});
array_push($aaida,${'aaid'.$activeagentsfec});
$activeagentsfec++;
}
// explode each inprogress call array
$activecallsfec=0;
$actida= array();
$acfida= array();
foreach ($sfipc as $acvalue)
{
${'acdetails'.$activecallsfec} = explode("'",$acvalue);
${'actid'.$activecallsfec} = ${'acdetails'.$activecallsfec}[5];
${'acfid'.$activecallsfec} = ${'acdetails'.$activecallsfec}[7];
array_push($actida, ${'actid'.$activecallsfec});
array_push($acfida, ${'acfid'.$activecallsfec});
$activecallsfec++;
}
// explode each unvailable agent
$unavailableagentsfec=0;
$uaaida= array();
foreach ($sfuaa as $uavalue)
{
${'uadetails'.$unavailableagentsfec} = explode("'",$uavalue);
${'uaaid'.$unavailableagentsfec} = ${'uadetails'.$unavailableagentsfec}[3];
array_push($uaaida, ${'uaaid'.$unavailableagentsfec});
$unavailableagentsfec++;
}
// create available agent array by id
$aaafec=0;
$aada= array();
foreach ($aaida as $aaidavalue)
{
if (in_array($aaidavalue,$actida,true))
$aaafec++;
elseif(in_array($aaidavalue,$acfida,true))
$aaafec++;
elseif(in_array($aaidavalue,$uaaida,true))
$aaafec++;
else
array_push($aada, $aaidavalue);
}
// available agent arry by ivr
$aadl= array();
foreach ($aada as $aadavalue)
{
$aaaivrsv= array_search($aadavalue,$aaida,true);
array_push($aadl,$aaivra[$aaaivrsv]);
}
Given what you were saying in the comments, I'll try to give you some useful thoughts...
You carry out much the same process to parse $sfaa, $sfipc, and $sfuaa - explode, get certain columns. If you had some way to abstract that process, with a generic function for the parsing, that returns the data in a better format, called three times on each array, you'd see better through your code.
In the same way, your process is tightly coupled to the current state of the data - e.g. ${'acdetails'.$activecallsfec}[5]; is your fifth item today, but will it always be? Something generic, where you seek an column by name, might save you a lot of trouble...
finally, when merging data, if the data is sorted before hand the merge can be a lot quicker - seeking N items in a list of M, with an unsorted list takes O(n*m) operations, but if both are sorted it's O(min(m,n)).
I've taken the time to go through your code... Unless you're usign some of its variables elsewhere, here is a shorter equivalent:
// formula needed to filter above results and fill $aadl array
// explode each active agent array
$aaivra= array();
$aaida= array();
foreach ($sfaa as $aavalue)
{
$a = explode("'",$aavalue);
array_push($aaivra, $a[5]);
array_push($aaida,$a[1]);
}
// explode each inprogress call array
$actida= array();
$acfida= array();
foreach ($sfipc as $acvalue)
{
$a = explode("'",$acvalue);
array_push($actida, $a[5]);
array_push($acfida, $a[7]);
}
// explode each unvailable agent
$uaaida= array();
foreach ($sfuaa as $uavalue)
{
$a= explode("'",$uavalue);
array_push($uaaida, $a[3]);
}
// create available agent array by id
$aada= array();
foreach ($aaida as $aaidavalue)
{
if (!in_array($aaidavalue,$actida,true) &&
!in_array($aaidavalue,$acfida,true) &&
!in_array($aaidavalue,$uaaida,true))
array_push($aada, $aaidavalue);
}
// available agent arry by ivr
$aadl= array();
foreach ($aada as $aadavalue)
{
$aaaivrsv= array_search($aadavalue,$aaida,true);
array_push($aadl,$aaivra[$aaaivrsv]);
}