how can i use values in array ? (php) - php

I wanna use values in array of array like:
$result = $conn->query("SELECT performer,file_id,title,duration FROM
databasebot WHERE performer = '$message' or title = '$message'");
$poets = array(
"keyboard" => array()
);
while ($row = mysqli_fetch_row($result)) {
$poets['keyboard'][] = array($row[2],$row[1]);
}
I wanna echo $poets values of $row[1]. How can I do that?

Loop through the array in $poets['keyboard']. In each element, $poets[1] will be in the [1] sub-element.
foreach ($poets['keyboard'] as $kb) {
echo $kb[1];
}

Related

How can I encode a json of a multiline result?

I try to encode my result in a json but it doesn't really work. When the query has more than one result than it doesn't work. When the result has only one line, than everything works fine.
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
}
Try this code
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
$i = 0;
while ($row = mysqli_fetch_assoc($sql)) {
$array[$i] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
$i++;
}
//RETURN JSON ARRAY
echo json_encode ($array);
}

How can i get Array values to separate php variables

I am trying to retrieve records in MySQL DB.I want to retrieve all the records belong to the img_path column.from the following code I am getting results as an array.but iw ant them as separate variables.
My code
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = array(
'img_path' => $row['img_path'],
);
}
print_r($productitems);
Current Output
Array (
[0] => Array ( [img_path] => img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png )
[1] => Array ( [img_path] => img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg )
[2] => Array ( [img_path] => img ) )
expected output
$variable1 = img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png;
$variable2 = img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg;
You can use extract function like this:
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = $row['img_path'];
}
extract($productitems, EXTR_PREFIX_ALL, "variable");
echo $variable_0;
echo $variable_1;
echo $variable_2;
You can do that :
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $k => $row) {
$varName = 'var' . $k;
$$varName = array(
'img_path' => $row['img_path'],
);
}
And you will have access to $var0, $var1, and so forth.
You might use, extract() function. Docs here
The extract() function imports variables into the local symbol table
from an array.
This function uses array keys as variable names and values as variable
values. For each element it will create a variable in the current
symbol table.
This function returns the number of variables extracted on success.
Use list().
http://php.net/manual/en/function.list.php
From the manual:
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
You can also use the following code, where you do not need to use an additional function like list() or extract(). It is also a very minimalistic approach.
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $key => $row) {
${'img_path_'.$key} = $row['img_path'];
}
/*
Output:
["img_path_0"]=>
string(50) "img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png"
["img_path_1"]=>
string(50) "img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg"
["img_path_2"]=>
string(3) "img"
*/

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

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

How can i put my database result in 3 dimensional array?

This is my code
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
is there any way to extract title,text,date from $result and put them into 3 dimensional array?
What about
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;
while( $row = mysql_fetch_assoc( $result ) {
$array[$i] = array();
// i'm just guessing at what sort of array you want
$array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
$i++;
}
I'd be interested to know what the ... you need a three-dimensional array for but ok:
$dim = array();
$result = mysql_query(...);
while ( $row = mysql_fetch_assoc($result) )
// Whatever you want to save in that particular bucket,
// I'll be using the result set
$dim[$row['title']][$row['text']][$row['date']] = $row;
Strange, ...
If we are already guessing, here is mine:
$results = array();
while(($row = mysql_fetch_assoc($result))) {
$results[] = $row;
}
which will create an array like this:
array(array('title' => 'foo',
'text' => 'bar',
'date' => 'baz'),
//...
)
I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)
One of the comments under the documentation of mysql_fetch_array has an answer to this:
(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
$i=0;
$keys=array_keys(mysql_fetch_array($result, $numass));
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
foreach ($keys as $speckey) {
$got[$i][$speckey]=$row[$speckey];
}
$i++;
}
return $got;
}
?>
You should then be able to use this function as
<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>

Categories