Create an associative array in php with dynamic key and value - php

I want to create an associative array in php with dynamic key and also a dynamic value from a particular mysql table.
The table name is monthly_salary with a two column named month and salary respectively.
I get the data inside it:
$sql = mysql_query('SELECT * FROM monthly_salary');
$sql2 = mysql_query('SELECT * FROM monthly_salary');
Then assigned and concatenated the collected data to $mon and $sal:
$mon = "";
$sal = "";
while($row = mysql_fetch_array($sql)){
$mon .= $row['month'].", ";
}
while($row = mysql_fetch_array($sql2)){
$sal .= $row['salary'].", ";
}
After that I've converted it to array and concatenate it until it became and associative array:
$monArray = array(substr(trim($mon), 0, -1));
$salArray = array(substr(trim($sal), 0, -1));
$key = "";
$keyWithVal = "";
foreach($monArray as $k){
$key .= $k." => ";
}
foreach($salArray as $k){
$keyWithVal .= $key.$k.",";
}
$associativeArray = array(substr(trim($keyWithVal), 0, -1));
My Problem is that when I've echo it the result is always like this
3500=>Jan=>3500:
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}
So how can I fix it and with the correct output Jan=>3500?

You are way over-complicating this problem. This can be done simply, with fewer loops.
First, you only need to run the SQL once. Second, build the array in the 1st loop.
$sql = mysql_query('SELECT * FROM monthly_salary');
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
// Put the values into the array, no other variables needed
$associativeArray[$row['month']] = $row['salary'];
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}

Why don't you just do:
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
$associativeArray[$row['month']] = $row['salary'];
}

Following worked for me for creating associative array. array_push don't work on associative array but using unary operator does work:
$associativeArray += [$key => $value];

Related

PHP - Array in implode

I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.

PHP -> PDO Update Function using Foreach array merge

The following code is supposed to check for the column names of a table. Then check to see if a corresponding variable has been $_POST and if it has add it to the $SQL. I believe there is a problem with the array that contains a series of arrays but I don't know how to dix it.
$where = $_POST['where'];
$is = $_POST['is'];
$table = $_POST['table'];
$sql = "UPDATE $table SET";
$array = array();
$columnnames = columnnames('blog');
foreach ($columnnames as $columnname){
if($_POST[$columnname]){
$sql .= " $columnname = :$columnname,";
$array .= array(':$columnname' => $_POST[$columnname],);
}
}
$sql = rtrim($sql,',');
$array = rtrim($array,',');
$sql .= " WHERE $where = '$is'";
$q = $rikdb->prepare($sql);
$q->execute($array);
For the sake of comprehension please except that $columnnames = columnnames('blog'); works as it does.
Change this:
$array .= array(':$columnname' => $_POST[$columnname],);
to this:
$array[':$columnname'] = $_POST[$columnname];
and after that use rtrim only on $sql.
the problem is here $array .= array(':$columnname' => $_POST[$columnname],);
you have a , part of the value which is not literal. change it to be like
$array .= array(':$columnname' => $_POST[$columnname] . ",");
You can also add your column names and values to an array and implode(",", $array) so you don't have to use rtrim
Instead of using
$array .= array(':$columnname' => $_POST[$columnname],);
and applying rtrim on results, I'd suggest the easier and failsafe method:
$array[':$columnname'] = $_POST[$columnname];

How to add manual key and value to dynamically created array?

Okay I need to ask
I'm building arrays in this way:
$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
$array1[] = $k;
}
and I want to add a manual key and value to $array1
I've tried $array1[]['admin']
and $array1['admin'][]
and array_push($array1['admin']=1)
and array_push($array1, 'admin' => 1)
and array_push($array1[], 'admin' => 1)
admin key is always going out of builded array
Just set a key to a value:
$array1['admin'] = 1;
Or:
$array1[] = $k + array('admin' => 1);
You are using mysql_fetch_object which returns object not array.
So you should do:
$k->admin = 1;
$array1[] = $k;
You'll need to do the following if you intend on constructing your arrays in this manner.
$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
$array1[] = Array("admin" => $k);
}

What is the best way to generate a condensed array like this in PHP?

I have an array like:
$arr[0] = ("1-3-2011","1","15"); //date(dd-mm-yyyy),id,amt
$arr[1] = ("1-4-2011","2","5");
$arr[2] = ("12-3-2011","6","20");
$arr[3] = ("1-3-2011","10","10");
$arr[4] = ("12-3-2011","3","10");
$arr[5] = ("1-4-2011","5","15");
$arr[6] = ("1-3-2011","7","15");
From this I need to generate a condensed array like
$newarr[0] = ("1-3-2011","1,7,10","40");
$newarr[0] = ("1-4-2011","2,5","20");
..
...
Basically the first one is a multidimentional array, containing date,id, and amount. In the new array, I need to condense the previous one for each unique date, ids as a csv string for duplicate dates, and amounts added.
What's the most efficient way to do this, performance wise?
Something like this should do it:
$newarr = array();
foreach($arr as $row) {
if(!isset($newarr[$row[0]])) {
$newarr[$row[0]] = array('ids' => array(), 'amount' => 0);
}
$newarr[$row[0]]['ids'][] = $row[1];
$newarr[$row[0]]['amount'] += $row[2];
}
foreach($newarr as $key => &$row) {
$row = array($key, implode(',', $row['ids']), $row['amount']);
} unset($row);
Working example:
http://codepad.org/UmiDKLYJ

PHP - Add String to Array

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);

Categories