Multi dimensional array - php

Have just come across a problem where I believe this is the solution.
At the moment I have the following code:
function siteUsers()
{
global $database;
$q = "SELECT username, id FROM ".TBL_USERS."";
return mysql_query($q, $this->connection);
}
function generateUserArray()
{
$u = array();
$i = array();
$result = $this->siteUsers();
while( $row=mysql_fetch_assoc($result))
{
$u[] = $row['username'];
$i[] = $row['id'];
}
return $u, $i;
}
As you can see, when I then go onto use foreach, the u and i get split apart.
Is there anyway that I could keep them together?
foreach ($u as $username) {
echo"<option value='$i'>$username</option>";
}
What I need it the option value to be the id and the visual value to be the username.
Is this possible?
Thanks

Use an associative array linking the ID to the username. I'm assuming here the IDs are unique.
$users = array();
while( $row=mysql_fetch_assoc($result))
{
$users[$row['id']] = $row['username'];
}
return $users;
Then:
foreach ($users as $id => $username)
{
echo "<option value='$id'>$username</option>";
}

foreach($u as $idx => $username)
{
echo"<option value='".$i[$idx]."'>$username</option>";
}
assuming equal length and that php function can return two values :\

Related

Retrieve data with foreach from return array function

I'm having troubles with my function and how to retrieve the data. Here is what i got.
public function getImages()
{
$array = array();
//Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
return $array;
}
}
Now I'm calling this function but i can not use foreach to access the array.
include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');
$users = new User;
$users->getImages();
foreach ($users as $value) {
echo $value["username"];
}
What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.
A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:
$userDAO = new User;
$users = $userDAO->getImages();
foreach ($users as $value) {
echo $value["username"];
}
You just need to put the return statement out of the while loop.
public function getImages() {
$array = array(); //Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
}

get array values with a function in PHP

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

PHP Reference for MySQL query

My function:
function sql_query($s, $x) {
$query = mysql_query($s);
global $mysql;
while($mysql = mysql_fetch_array($query)) {
return;
}
}
Now it's work only with $mysql variable:
echo $mysql['username'];
How to make it works only with:
sql_query("select * from users where id = '1' limit 1", "varname");
$varname['username'];
I want to set a SQL Query and Variable name in function, like:
sql_query("sqlquery", "variable");
echo $variable['id'];
Thanks for reply!
function sql_query($s, &$x) {
global $mysql;
$query = mysql_query($s);
$result = mysql_fetch_array($query);
foreach($result as $key => $value) {
$x[$key] = $value;
}
}
This should assign each variable that is returned by the query to a key in array $x (assuming it is an array). Notice that I am passing $x by reference instead of by value, eliminating the need to return anything.

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

How to store values from foreach loop into an array?

Need to store values from foreach loop into an array, need help doing that.
The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated.
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
Declare the $items array outside the loop and use $items[] to add items to the array:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);
Use
$items[] = $username;
Try
$items = array_values ( $group_membership );
<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>
You can try to do my answer,
you wrote this:
<?php
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
?>
And in your case I would do this:
<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
$items[] = $username;
} ?>
As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)
<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
$items[] = $username;
}
?>
while is faster, but the last example is only a result of an observation. :)
This is how you do it:
foreach($orders as $item){
$transactionIds[] = $item->generated_order_id;
}
dump($transactionIds);
This is assuming $orders collection has a field called 'generated_order_id'.
$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
Just try the above in your code .
Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>

Categories