I have this code for print result for PHP json output:
$value = array();
$return_arr = array();
$row_array = array();
$fileName = Access::FETCH("SELECT name ,id FROM " . TAGS . " GROUP BY name ORDER BY name ASC");
foreach($fileName as $key => $value)
{
$row_array['id'] = $value['id'];
$row_array['text'] = $value['name'];
$rows2[] = $row_array;
}
$ret = array();
echo json_encode($rows2);
result is:
[{"id":406,"text":"404"},{"id":405,"text":"tag1"},{"id":404,"text":"tag3"},{"id":401,"text":"tag4"}]
But in action i see id value not Between ""(example:"id":406) i need to this format for json_encode:
{"id":"405","text":"tag1"}
How do create this?!
First, if you write your query slightly differently then it appears that you do not have to copy the values into a temporary array:
$fileName = Access::FETCH("SELECT id, name AS text FROM " . TAGS . " GROUP BY text ORDER BY text ASC");
json_encode($fileName);
In other words, name AS text just changes the key at the source, so to speak.
As for the integer not being a string. Before you do anything you should consider if it even matters. If it does, then correcting it is as simple as just casting them to strings:
$row_array['id'] = (string) $value['id'];
Or if you use my suggestion of the SQL query then you can just loop over the data and cast it, in place:
foreach ($fileName as & $value) {
$value['id'] = (string) $value['id'];
}
json_encode($fileName);
If you need numeric data to be represented as a string all you have to do is explicitly cast it to a string prior to calling json_encode like this:
$row_array['id'] = (string)$value['id'];
Convert $value['id'] to string should help:
$row_array['id'] = (string)$value['id'];
Related
I have a csv string and need to select rows having corresponding id.
And need to do something specific if a row doesn't exist.
$str = '1,2,3,4,5,6,7,8,9,10,11,12';
$st = $db->query("select *
from arts
where id in (" . $str . ")
order by field (id, " . $str . ")");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $el) {
// if ($el is missing) {echo 'the row is missing';} // how to do this?
else { ... }
}
The easiest option here, assuming you are stuck with the input CSV string, is to use FIND_IN_SET, something along these lines:
$sql = "SELECT id, FIND_IN_SET(id, :list) AS result FROM arts";
$str = "1,2,3,4,5,6,7,8,9,10,11,12";
$stmt = $db->prepare($sql);
$stmt->bindParam(':list', $str);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($arr as $el){
if ($el["result"] <= 0) {
echo "the row is missing for id " . $el["id"];
}
}
Rather than look at the records found, this code first keys the retrieved records on the id and then looks through the ID's you are looking for and if this record isn't found (using isset()) then process the not found part...
$arr = array_column($arr, null, "id");
$ids = explode(",", $str);
foreach($ids as $el){
if(!isset($arr[$el])) {
echo 'the row is missing';
} else{
echo 'the row is there';
}
}
In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php
So, my problem is: I capture data from my database, part of this date is inside a json array. Then, I put all of the json information into an array. Like this:
foreach ($corporativos->lista as $value):
$classe_row = '';
$input = $value["info_adicionais"];
$data = json_decode($input,true);
echo $data['andamentos'];
$arr1 = explode(',',$data['andamentos']);
endforeach;
Now, I need to populate a table with this information. But I can't explode the string.
The strings are like this:
" Name name name, 123123/uf; Name name, 123123/uf " and so on.
First trim the string and explode on the ";" sign and on the "," sign as:
$str = " Name name name, 123123/uf; Name name, 123123/uf ";
$str = trim($str);
$temp = explode(";",$str);
if (count($temp) > 0) {
foreach ($temp as $key=>$value) {
$result[] = explode(",",$value);
// OR
$result[whatever the id you want here] = explode(",",$value);
}
}
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];
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);