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).
Related
When populating a dropdown list using a foreach statement on array, it display a single item as a string. however, it can populate the list correctly using this syntax ["test1","test2"]
foreach($dataNew[$i]['message'] as $x => $item){
$myMessage[]='"'.$item['Lots'].'"';
}
$lots=[implode (',', $myMessage)];//does not work
//$lots=['4342355555555#1', '32335455#5'];//works fine
$dataNew[$i]=['Lots'=>[$lots]];
Any ideas?
Here is an example of corrext concatination, assuming some details of your problem, which are not quite clear by now.
Assuming: the $dataNew parameter holds an array of strings at [$i]['message'] which contains lots, which are seperated by commas, and come from some statistical process.
The output shall be an two-dimensional array, which merges all lots of one iteration into one list. So the reslut is a list of lists of lots (foreach $i).
$currentLotsList = $dataNew[$i]['message'];
//iterating over the lots of the current sample - which are a chain of strings seperated by commas
foreach($currentLotsList as $csvLots){
//getting the lots into an array
$currentLotsArray = explode(",", $csvLots);
//adding this list to the major list of $i,
if(!isset($dataNew[$i]['Lots']) ){
//createing the array if not set now.
$dataNew[$i]['Lots'] = [];
}
$dataNew[$i]['Lots'] = array_merge($dataNew[$i]['Lots'], $currentLotsArray);
}
e.g. I have this Product Id values 31,32 from database. I want to put them on array. So, I can use the values for foreach.
What I want to achieve:
I want to get the stock of each product from database according to the given values (31,32).
What I tried:
$product_values = '31,32'; //this values can be different, sample values only
$arr_product_values = array();
$arr_product_values[] = $product_values;
foreach ($arr_product_values as $prod_id) {
echo $prod_id;
}
Expected output:
31 & 32
$arr_product_values[] = $product_values;
That doesnt mean you have a new array with those 2 values now. You just took a comma separated string and assigned it to an array element, that doesnt make it an array itself.
$arr_product_values = array(31,32);
Does.
Now you can loop over it
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();
We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;
I've done a fair bit of googling and couldn't find anything that works, I'm just getting nothing back, this is probably something simple but there's a lot of variations that don't seem to match what I'm doing.
To give you an overall idea what I'm at, I'm accessing an API and getting back info as an object. There are comments and attachments, these are in separate arrays.
What i want to do is display the comments and attachments all together in the order of the date and time not separately.
I figured the best way is to create a loop through the comments array, then create a loop through the attachment array, then join both and sort by the date (epoch) and then loop through the whole merged loop echoing what i want. That should provide some context, right now i just want to create the multidimensional array for comments and i can figure out the rest.
$comments_holder = array();
//total number of comments in the array
$comment_total = $issue_json->fields->comment->total -1;
$i=1;
while ($i <= $comment_total)
{
//this is the date,time and timezone info for each comment
$raw_date = $issue_json->fields->comment->comments[$i]->updated;
$comments_holder[$i] = array();
//convert_sql_time just converts from 2012-11-04T16:33:00.936+600 into epoch time so i can sort the results later based on date
$comments_holder[$i]['comments_date'] = convert_sql_time($raw_date);
$comments_holder[$i]['comments_displayName'] = $issue_json->fields->comment->comments[$i]->author->displayName;
$comments_holder[$i]['comments_body'] = $issue_json->fields->comment->comments[$i]->body;
}
if everything is okay with data, this code will be enough for building such array:
$comments = $issue_json->fields->comment->comments;
$result = array();
foreach ($comments as $comment) {
$result[] = array(
'comments_date' => convert_sql_time($comment->updated),
'comments_displayName' => $comment->author->displayName,
'comments_body' => $comment->body,
);
}
print_r($result);
if comment->comments is an array, there is no need to keep it's count separately;
foreach is enough for iterating through the array and there is no need to keep separate variable for calculating array index;
[] notation will automatically increase array index and assigning array directly will do the trick(i.e. will result to multi dim array)