How to create php array from MySQL column? - php

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

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>';
}

PHP: Sorting MySQL result to multi-dimensional array

Now I'm tryin' to sort MySQL result to multi-dimensional array by type line in SQL
so, that's my code:
function getTableValues($table_name)
{
// $link = connect_db();
$front_end_query = "SELECT * FROM `".$table_name."` WHERE `type` = 'front_end'";
$front_end_query_result = mysql_query($front_end_query);
$cur_row = 0;
/*while ($line = mysql_fetch_assoc($queryresult))
{
$values = $line;
$cur_row++;
}*/
$front_end = mysql_fetch_assoc($front_end_query_result);
$i=0;
while ($line = mysql_fetch_assoc($front_end_query_result)){
#if ($line['type'] === 'front_end'){
# $line[$line['type']][$line['name']] = $line['value'];
# $line[$line['type']][$line['name']]['desc'] = $line['description'];
# $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name'];
# $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles'];
# $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles'];
#}
$values['front_end'][$line['name']] = $line;
$i++;
}
return $values;
}
And my MySQL table:
id type write_roles read_roles name value description visible_name
1 front_end 0 any title sometitle exampletitle Title
2 front_end 0 any description somedesc example Description
And that's what I want to get:
$config[(someType)][(SomeName)] = (value of line)
$config[(someType)][(SomeName)][(SomeOption)] = (value of option)
E.g.: $config['front_end']['title']['description'] that returns exampletitle
How I can do that?
UPD0: so I tried to echo my array with foreach, and it's returned just one row from my DB.
What I doing wrong?
$values = array(); //base array
while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch the rows
//in the base array create a new array under 'name'
$values[$line['name']] = array();
//for each item in the result set, add it to the new array
foreach ($line as $key => $value) {
$values[$line['name']][$key] = $value;
}
}

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'];
}

php array replicate format in while loop

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

mysql query to php array and display the array

$query2 = "SELECT * FROM `Listing` WHERE listingid = '{$myID}'";
if(!($result2 = # mysql_query($query2,$connection)))
echo "query failed<br>";
$result_array = array();
while($row2 = mysql_fetch_assoc($result2))
{
$result_array[] = $row2;
}
foreach ($result_array as $key => $val) {
echo "$key = $val\n";
}
Listing (Table) has 7 fields.
I get a bunch of "0 = Array"
How do I store mysql query results into php array and display them?
I want to have it as array first so i can sort them.
You are actually storing them. The code you have listed is storing them in array of arrays to see them you can modify the for with:
foreach ($result_array as $key => $val) {
echo "$key = " . print_r($val, true) . "\n";
}
$val is actually an array containing all the fields of a row.

Categories