php array replicate format in while loop - php

I want to output the result of a query so that the format is the same as:
$links = array(
'Link 1' => '/link1',
'Link 2' => '/link2'
);
So the query is
$query = "SELECT * FROM link";
$result = mysql_query($query, $connection) or die(mysql_error());
$row = mysql_fetch_assoc($result)
The field that need to be output are:
$row['link_title'] and $row['url']

This is probably a bit more complex then desired or necessary but would this work for you:
$a = 0;
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $k => $v) {
// Assumes table column name is 'link_title' for the link title
if ($k == 'link_title') {$title[$a] = $v;}
// Assumes table column name is 'url' for the URL
if ($k == 'url') {$url[$a] = $v;}
}
$a++;
}
$i = 0;
foreach ($title as $t) {
$links[$t] = $url[$i];
$i++;
}
print_r($links);
As #Class stated, if the link_title's never repeat than you could do something like this:
while ($row = mysql_fetch_assoc($result)) {
$array[$row['link_title']] = $row['url'];
}
Since the link_title's were unique both processes output:
Array (
[Moxiecode] => moxiecode.com
[Freshmeat] => freshmeat.com
)
Database table + contents:
id | link_title | url |
---+------------+---------------|
1 | Moxiecode | moxiecode.com |
---+------------+---------------|
2 | Freshmeat | freshmeat.com |

Are you looking for something like this:
$links = array();
while(foo){
$links[$row['link_title']] = $row['url'];
}
OR you can use which might cause overriding if the title is the same like in the example above
$link = array();
$title = array()
while($row = mysql_fetch_assoc($result)){
array_push($title, $row['link_title']);
array_push($link, $row['url']);
}
$links = array_combine($title, $link);
Also use PDO or mysqli functions mysql is deprecated. Here's a tutorial for PDO
EDIT: Example: http://codepad.viper-7.com/uKIMgp I don't know how to create a example with a db but its close enough.

You want to echo out the structure of the array?
foreach ($Array AS $Values => $Keys)
{
echo "Array Key: <b>". $Keys ."</b> Array Value:<b>". $Values ."</b>";
}
This will echo out the structure of your exampled array

Related

PHP combine matching rows from associative arrays from sql and display results in html

I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}

How to convert mysql_fetch_assoc array to [column,column] Format in PHP

This is my function
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`) AS `Provider State`,
sum(ROUND(medicare_provider_charge_inpatient_drg100_fy2011.`Total Discharges`, 2)) AS `Total Discharges`
FROM medicare_provider_charge_inpatient_drg100_fy2011
WHERE medicare_provider_charge_inpatient_drg100_fy2011.`Provider Name` LIKE '%" . $hospital_name . "'
GROUP BY CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`)"));
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row;
}
I want to display data in following format
[Provider State, Total Discharges],
[US-AL,2051],
[US-TN,6982]
the dump of $dataArray gives me
Array
(
[0] => Array
(
[Provider State] => US-AL
[Total Discharges] => 2051.00
)
[1] => Array
(
[Provider State] => US-TN
[Total Discharges] => 6982.00
)
)
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row["Provider State"]. "," .$row["Total Discharges"];
}
That should make your data into a single-dimensional-array.
You just need to work with the data to display the way you want. Print first the column names and then the data. I made this example to work for any number of fields:
// Print the first row with column names
$firstRow = array_keys(reset($dataArray));
$output = array();
foreach($firstRow as $val) {
$output[] = $val;
}
echo '['.implode(',',$output).']'."\n";
// Print all the data
foreach($dataArray as $row) {
$output = array();
foreach($row as $col) {
$output[] = $col;
}
echo '['.implode(',',$output).']'."\n";
}
If you need such structure of array, use this (but it is strange):
$newStructure = array();
$newStructure[] = "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
$newStructure[] = $row['Provider State'] . ',' . $row['Total Discharges'];
}
If you want to just display data, use this:
echo "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
echo = $row['Provider State'] . ',' . $row['Total Discharges'];
}

How to create php array from MySQL column?

I have such table:
id | name | link
---+--------------------------------------+---------------
1 |SAsasasdsa,Главная страница,Main page | addsad
I want to get array like that:
$arr = array('az'=>'SAsasasdsa','ru'=>'Главная страница','en'=>'Main page');
TRY
$qry = mysql_query('SELECT * FROM table');
//for multiple rows
$row = mysql_fetch_assoc($qry)) { $input[] = $row['name'] }
$key = array('az', 'ru', 'en');
foreach($input as $val) {
$output[] = array_combine($key,explode(',',$val));
}
echo "<pre>"; print_r($output);
Reference
array_combine

Storing data from SQL in array

I am trying to store the data from my sql database into an array. Currently I have this:
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
while($row = mysql_fetch_array($query))
{
$inspector = $row['name'];
}
The problem is that I have 8 rows of data. I need to store each 8 names from that database into an array. When I try this:
$inspector = array($row['name']);
It doesn't work.
If you want to store all of the names in an array, you need to define the array outside the scope of the while loop and append to it. Like this:
$nameArray = array();
while($row = mysql_fetch_array($query)) {
// Append to the array
$nameArray[] = $row['name'];
}
What you want is:
$inspector[] = $row['name'];
This will store all 8 names in an array similar to:
array(
[0] => name1
[1] => name2
[2] => name3
)
Lots of good answers. But if you do this often, you might want to write a little function:
mysql_field_array($sql, $fieldname)
{
$res = mysql_query($sql);
$a = array();
while($row = mysql_fetch_array($res))
{
$a[] = $row[$fieldname];
}
mysql_free_result($res);
return $a;
}
Replace this line...
$inspector = $row['name'];
...with this:
$inspector [] = $row['name'];
After that, the inspector array contains all the names.
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
$data = array();
while($row = mysql_fetch_array($query))
{
$inspector[] = $row;
}
for($i=0;$i<mysql_num_rows($row);$i++)
{
$data = $inspector[$i];
}
return $data;
Check it...

Structure of php JSON output

this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...

Categories