So I have this db with a table called users.
In here is column called work, which is currently empty for all users. I've made a list containing many job-titles, and now I want this to be added into the users table under work column.
I figured I'd do something with a array like this:
$input = array("worktitle1", "worktitle2", "worktitle3");
$rand_keys = array_rand($input, 1);
and then update rand_keys in a simple query:
$mysqli->query('UPDATE users SET work = '.$rand_keys.'');
However, when I did that, only a number value was inserted and it was the same for all of the xx users I haven in the db.
How can I fix so that it insert a random worktitle for every single row? And not the same worktitle for every users. I thought about doing rand() in the query, but am unsure of this works
BONUS QUESTION: If I want my array_rand to prioritise some worktitles (so in the db a specific worktitle will show 10% more times than others), how can I do that?
I am assuming that you have for loop or while or some array which you want to loop through and insert the dummy data in database table.
I think its because you have used array_rand before the for loop and then using inserting into the database of the random key which you had earlier
Eg:
<?php
$input = array("worktitle1", "worktitle2", "worktitle3");
foreach($somearry as $key => $values){
//Now you need to call the array_rand function
$randomKey = array_rand($input, 1); //This will return only the random key of the array
$randomWork = $input[$randomKey]; //This line will give you the random key value of the input array
//Now write your code *here* to insert this random value ie update query
}
Using while loop as per your request
while(some_condition){
//Now you need to call the array_rand function
$randomKey = array_rand($input, 1); //This will return only the random key of the array
$randomWork = $input[$randomKey]; //This line will give you the random key value of the input array
//Now write your code *here* to insert this random value ie update query
}
Even you can do the following hard coded way.
Note : This is just for the sake of demonstration for the user so that
he can understand it properly.
for($i = 0; $i < 10; $i++){
//Now you need to call the array_rand function
$randomKey = array_rand($input, 1); //This will return only the random key of the array
$randomWork = $input[$randomKey]; //This line will give you the random key value of the input array
//Now write your code *here* to insert this random value ie update query
$mysqli->query("UPDATE users SET work = '$randomWork'");
}
As written, your code selects one title at random and then updates all rows with that title, which is I think what you are saying. You need to loop through all users, select a title, and then set the title "WHERE userid='xxx'" or some other way of selecting specific users.
Weighted randomness. Take you array of titles and add extra entries for the ones you want to weight. If "CEO" is to be 10% more likely to be used, make sure the array has 10 entries of "CEO".
Related
i want to display in my system just one record with the same id.
for example: 01,01,02,02,03,03.
I just want to display 01,02,03.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
$number = "01,01,02,02,03,03";
$result = implode(',',array_unique(explode(',', $number )));
echo $result; // output 01,02,03
Happy Programming
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 have an array which contains sets of three similar named items; however, sometimes there's only two items in a set and I want to call these out.
<?php
$items = array(
'reviewpitfighter-1.138x88.jpg',
'reviewpitfighter-2.138x88.jpg',
'reviewpopfulmailsegacd-1.138x92.jpg',
'reviewpopfulmailsegacd-2.138x76.jpg',
'reviewpopfulmailsegacd-3.138x97.jpg'
);
?>
You'll note that there are two reviewpitfigher* items, and three reviewpopfulmailsegacd* items. I've started down a rabbit hole of loops and feel that there is something simple I'm just glossing over.
May be you can do this as a 2 stage process.
Stage 1:
Loop through the original array and form another set of array with its key as the value of this original array. Then save the repetition count in each of those new arrays.
Stage 2:
Loop through the new set of arrays and then pick out the arrays which has values less than 3 and retrieve its key.
Hope this helps!!
Here's the solution I came up with, sorry it took so long to post.
foreach($images as $value){
$lastItem = explode('-', $images[$count - 1]);
$parts = explode('-', $value);
if(preg_match('/^1/', $parts[1]) && $count != 0){
if(preg_match('/^2/',$lastItem[1])){
$imgurl = preg_replace('/^p?review/','',$lastItem[0]);
$sql = 'SELECT field FROM table WHERE field = "' . $imgurl . '"';
$result = $dbConn->FetchArray($dbConn->Query($sql), MYSQL_ASSOC);
$array[$imgurl] = $result;
}
}
$count++;
}
I get an array of all the images, then I check to see if I'm looking at the first image, if I am then I see if the last image I looked at was the second image. At this point I then call into the database to get some information to display a neatly messaged out put of what reviews are missing a third image. In the end $array contains this list which I can loop over.
I have the following array:
$masterlist=[$companies][$fieldsofcompany][0][$number]
The third dimension only exists if the field selected from $fieldsofcompany = position 2 which contains the numbers array. Other positions contain regular variables. The 3rd dimension is always 0 (the numbers array) or Null. Position 4 contains numbers.
I want to cycle through all companies and remove from the $masterlist all companies which contain duplicate numbers.
My current implementation is this code:
for($i=0;$i<count($masterlist);$i++)
{
if($masterlist[$i][2][0][0] != null)
$id = $masterlist[$i][0];
for($j=0;$j<count($masterlist[$i][2][0]);$j++)
{
$number = $masterlist[$i][2][0][$j];
$query = "INSERT INTO numbers VALUES('$id','$number')";
mysql_query($query);
}
}
Which inserts numbers and associated IDs into a table. I then select unique numbers like so:
SELECT ID,number
FROM numbers
GROUP BY number
HAVING (COUNT(number)=1)
This strikes me as incredibly brain-dead. My question is what is the best way to do this? I'm not looking for code per se, but approaches to the problem. For those of you who have read this far, thank you.
For starters, you should prune the data before sticking it into the database.
Keep a look up table that keeps track of the 'number'.
If the number is not in the look up table then use it and mark it, otherwise if its in the look up table you can ignore it.
Using an array for the look up table and with keys being the 'number' you can use the isset function to test if the number has appeared before or not.
Example pseudo code:
if(!isset($lookupTable[$number])){
$lookupTable[$number]=1;
//...Insert into database...
}
Now that I think I understand what you really want, you might want to stick with your two-pass approach but skip the MySQL detour.
In the first pass, gather numbers and duplicate companies:
$duplicate_companies = array();
$number_map = array();
foreach ($masterlist as $index => $company)
{
if ($company[2][0][0] === null)
continue;
foreach ($company[2][0] as $number)
{
if (!isset($number_map[$number])
{
// We have not seen this number before, associate it
// with the first company index.
$number_map[$number] = $index;
}
else
{
// Both the current company and the one with the index stored
// in $number_map[$number] are duplicates.
$duplicate_companies[] = $index;
$duplicate_companies[] = $number_map[$number];
}
}
}
In the second pass, remove the duplicates we have found from the master list:
foreach (array_unique($duplicate_companies) as $index)
{
unset($masterlist[$index]);
}