I need to produce an array that is formatted as follows:
Array(
Array([100000116287110]=>
Array([name] => Bryce [image] => abcd.png))
Array([100003019827186]=>
Array([name] => Ross [image] => defg.png))
)
The data to produce the array comes from 2 different sources and is fed to a function.
The function call is lookupUserData($a, array(“name”, “image”)) //this has been set up so other details from the user table can be called simply by adding the field name in the array.
$a is formated as $a = “100000116287110,100003019827186”
The current code I am using for the function is as follows:
function lookupUserData($f,$u)
{
$f = explode(",",$f); //user id from string – converts string to array ([0] =>100000116287110 [1] =>100003019827186)
$u = implode(",",$u); //fields to extract – converts array(“name”,”image”) to name,image
$r=array(); //define results array`
$nr = count($f); //count number of ids to process
for($i=0; $i<$nr; $i++) { //process each id in $f array
$r[]=$f[$i];
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
array_push($r, $val); //add values to array $r
}
print_r ($r); //check array output – testing only
return $r; //return array for processing
}
This however returns the result as follows:
Array(
Array([0]=>[100000116287110]
Array([name] => Bryce [image] => abcd.png))
Array([1]=>[100003019827186]
Array([name] => Ross [image] => defg.png))
)
I know I have missed something simple but just cannot seem to get this right!
Something like this:
$r= array();
for($i=0; $i<$nr; $i++) { //process each id in $f array
$res = mysql_query("SELECT {$u} FROM users where id ={$f[$i]}"); //query user table
$val= mysql_fetch_assoc($res); //return requested fields ($u) from user table
$r[$f[$i]] = $val;
}
Related
This question already has answers here:
Generate PHP array from MySQL with key value from "id" column
(4 answers)
Closed 3 years ago.
I use the following PHP lines to query data from a MySQL table.
I want to store the query results in an array and then later on the same page print specific values from this array based on their ID.
I am new to PHP and hope someone can help me with an explanation on what I am doing wrong or missing here. I am assuming I create the array wrongly.
My PHP (relevant part, variables are defined earlier on this page):
$con = mysqli_connect($host_name, $user_name, $password, $database);
$result = mysqli_query($con, "SELECT id, $col FROM $table ORDER BY id");
$rows = array();
if($result)
{
while($row = mysqli_fetch_array($result))
{
print_r($row);
}
}
var_dump($rows);
My current array (when printed as above):
Array ( [0] => testid1 [id] => testid1 [1] => testval1 [en] => testval1 ) Array ( [0] => testid2 [id] => testid2 [1] => testval2 [en] => testval2 ) Array ( [0] => testid3 [id] => testid3 [1] => testval3 [en] => testval3 ) array(0) { }
Example:
E.g. I want to print the value for the item with ID = "testid2" from this array.
In this case the printed value should be "testval2".
Many thanks in advance,
Mike
Store your data as:
for
(
$set = array();
$row = $result->fetch_assoc();
// use value of `id` as the key in your `$set`
$set[$row['id']] = $row
);
print_r($set);
// later:
$id = 1;
echo $set[$id]['en'];
// or
echo $set[$id][$lang];
You can just use fetch_all() and then column search
$con = mysqli_connect($host, $username, $password, $database);
$result = mysqli_query($con, "SELECT id, $lang FROM $table ORDER BY id");
$set = $result->fetch_all(MYSQLI_ASSOC);
$key = array_search('testid2', array_column($set, 'id'));
echo $set[$key]['en'];
You can use array_combine() with array_column() to convert the query output (in rows and columns) to key-value format (key being the id, and value being the en column):
// $set array is populated using fetch_assoc
// create a new array using $set
$modified_set = array_combine(array_column($set, 'id'),
array_column($set, 'en'));
// Now, you can access the en value for a specific id like this:
// eg: for id = testid2
echo $modified_set['testid2']; // will display testval2
I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm
I want three element in associative array, so far am successful in getting two in the array.
$sql = "SELECT * FROM `notification_table` ";
$resultsd1 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($resultsd1);
$associativeArray = array();
while ($row = mysqli_fetch_assoc($resultsd1))
{
$associativeArray[$row['name']] = $row['price'] ;
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id .' ';
}
And am getting the response like this
name1=>24.725 name2=>24.265
Now i want to add another column in array as well and the name is column is notification_check .
Am not able to get how to add three columns in a single array. Any help will be appreciated.
I want the output like name1=>24.725=>yes_notification name2=>25.43=>no_notification
And when i print_r($row) is show this output Array ( [sno] => 1 [name] => name1 [price] => 23 [notification_check] => yes_notification)
You could shorten this and use mysqli_fetch_all to create an array of all of the data and then manipulate the array using array_column to create the index...
$result = mysqli_fetch_all($resultsd1, MYSQLI_ASSOC);
$associativeArray = array_column($result, null, 'name');
Have a PHP factory with a sub class that queries either one or more unrelated tables in a database. The class takes a table name as a parameter and returns an array object.
When more than one table is required, I would like a way to delimit each tables result set in to its own array. The class would then return a multi-dim array.
I would prefer to not instantiate another instance of the factory. Here is the current query/result code block. I've left out all the other non-essential code for brevity
// if array has more than one table to query,
// run queries on each table
$count = count($tname);
if ($count>1) {
foreach ($tname as $value) { //each table name in array
/* $query = "SELECT s.* FROM $value s"; tried with table alias */
$query = "SELECT * FROM $value";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
} else {
return false;
}
}
return $result;
// else if only one table to query
} else {
$string = $tname; //table name
$query = "SELECT * FROM $string";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
} else {
return false;
}
}
With more than one table, would return something like:
Array
(
[0] => Array
(
[team_id] => 3
[team_name] => Maverics
)
[1] => Array
(
[team_id] => 4
[team_name] => Stallions
)
[3] => Array
(
[fld_id] => 1
[fld_name] => 6v6-1
)
[4] => Array
(
[fld_id] => 2
[fld_name] => 8v8-2
)
)
Where 0,1 are from one table and 3,4 are from another.
Thank you in advance
Figured it out... Simple actually, just didn't see it before I asked the questions. I changed:
$result[] = $row;
to
$result[$value][] = $row; //line 11 in code block example
This now returns the array with each table name as the array name for the result set.
Thanks anyway,
I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!