How to loop mysql result inside an array - php

I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?

You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO

You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);

Related

When I try to access to array items I only get the 1. one

Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

Fetch data from mysql using associative array and implode (codeigniter + MySql)

I've gathered data from multiple MySql tables and stored them as associative arrays using a foreach loop with the query.
I would like to use those associative arrays and the implode method in the mysql query to gather more data from a separate table.
I know that with the implode method, when dealing with Indexed arrays, you can just insert the array directly in the "implode section". But with associative arrays, I am unsure how to call all the available arrays and insert them in the query.
Please refer to the attached image for a detailed illustration explaining it further.
Below is also a portion of my code
public function user_implode()
{
$s_id = array(
"id" => 383
);
$count = 0;
foreach ($query->result() as $row)
{
$count = $count + 1;
$loop_number[$count] = $row->id;
}
$this->db->from('occupation');
$this->db->where_in('id',implode("','",$loop_number[$count]));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->id;
}
echo 'Total Results: ' . $query->num_rows();
}
THANKS ALOT
The second parameter to where_in() should be an array.
You are generating a string with implode() and only of the last value of the array instead of the whole array.
So all you need is:
$this->db->where_in('id', $loop_number);
And I don't see where $query comes from, it seems to be undefined when you use it in the first loop in your method.
Apart from that you should initialize your variable, $loop_number = []; before the loop.

How to print only index of an array

Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}

array to string conversion error, need to explode and then implode

I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);

Categories