I am pretty new to php and could sure use some help understanding how to get my result the way I need it from a database query.
What I need is an associative array like this, 'bla'=>'bla'. What I am getting from my foreach loop is this from a print:
[0] => Array
(
[0] => test0
[name] => test0
[1] => 1
[customer_id] => 1
)
[1] => Array
(
[0] => test
[name] => test
[1] => 2
[customer_id] => 2
)
Here is my loop:
foreach($res as $key=>$val)
{
// have no idea..
}
Can someone please help me to format my results so that they are like 'index'=>'value'
Thanks for any help.
Here is a sample code that uses a foreach but yet pulls an association. I don't get it. I am thinking that my result set with the indexes are because I am not writing the loop correctly. Here is the code that uses the foreach
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Here is the part of the database class that I am using to fetch the results.
$returnArray = array();
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row)
$returnArray[$i++] = $row;
}
mysql_free_result($result);
return $returnArray;
After using the code that was given to me to omit the index numbers, here is what I am now left with. Its close but not what I need.
Array
(
[id] => 1
[cust] => bobs auto
)
This is what the above line should read like
'1' => 'bobs auto'
What I am trying to do is to format the output for a JSON call for a suggestion box.
I cannot get this to work. Here is everything after my db connection.
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
$out[$key['id']] = $val['cust'];
}
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out_array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
OK, I think I am coming down to the home stretch. I have what I need sort of. This is the code I have so far.
$out_array = array();
foreach($items as $key)
{
$out_array[$key] = $val;
//$out_array[$key['id']] = $key['cust'];
}
Notice that the commented line does not work, It outputs like the id twice but the line that isn't commented out works just fine. Here is the output from that.
Array
(
[8] =>
[FAT BURGER] =>
)
From this point, would I just use another foreach to iterate over the entire set of data? The array output you see above is from a print_r.
This is what I now have and it returns the correct association however, I must comment out the strpos condition to get any results back and I don't know why. Am I correct in nesting these foreach loops like I have?
$out_array = array();
foreach($items as $key)
{
// $out_array[$key] = $val;
$out_array[$key['id']] = $key['cust'];
foreach ($out_array as $key=>$value)
{
if (strpos(strtolower($key), $q) !== false)
{
echo "$key|$value\n";
}
}
}
So you don't want the numeric indexes in your array? You must be using mysql_fetch_array(), which returns your results with both numeric and string keys. Use mysql_fetch_assoc() to get an array with only the string keys (the string being the column name).
Try something like this. It works by skipping the integer indices, and putting the non-integer indices into an output array.
$out_array = array();
foreach($res as $key=>$val) {
if(is_int($key)) {continue;}
$out_array[$key] = $val;
}
EDIT:
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
}
$out[$out_array['id']] = $out_array['cust'];
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Assuming this is a MySQL database, the results, if more than one, are returned as a multidimensional array.
When you run the query:
$query = "SELECT * FROM Table WHERE ...";
$query = mysql_query($query);
while($info = mysql_fetch_assoc($query)){
//$info is now a single row, associative array
echo print_r($info);
}
the echo print_r displays the results the way you are looking for them now 'index'=>'value'
EDIT: based on comments.
If you absolutely CAN'T get rid of the mysql_fetch_array then you'll have to hack the code. It's not clean and I strongly advise refactoring but below is the code you'll need to create an array of field name indexes only from what you're given
$my_array = array();
$info = $data[0]; //grab the first row of your data set from the original question.
foreach($info as $index => $value){
if(!is_int($index)){
$my_array[$index] = $value;
}
}
The newly created $my_array will be in the format you're looking for.
You got this array from a query and result function from PHP, yeah?
If you were using mysql, it's actually easier to do it like below.
$query = mysql_query("SELECT * FROM dbname"); //Create the query to your database
while($data = mysql_fetch_array($query)) //Loop through our results from the query
{
echo($data['fieldname']."<br/>"); //echo out data through the loop
}
$ret = array();
foreach($rows as $row)
{
$ret[$row['id']] = $row['cust'];
}
$json = json_encode($ret);
echo $json;
// Prints something like:
//
// {1:'bob'}
Note the use of json_encode.
Ok, regarding my last question. I was incorrect in nesting the foreach loops. I also had a typo in my code. It is working, finally. Thank you to all that have helped me!
Related
I've looked on stackoverflow for the answer, but no one explains it properly.
I have a while loop that works:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
And when I print out the array:
Array ( [team_id] => 26 [team_points] => 100 )
But my foreach returns an invalid argument.
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
I've tried many different ways but nothing works.
Thanks!
Problem is in fetching data from DB. Modify your while loop like this:
info = array();
while($get_info = mysql_fetch_array($info_result)){
$temp_info = array();
$temp_info['team_id'] = $get_info['team_id'];
$temp_info['team_points'] = $get_info['team_points'];
$info[] = $temp_info;
}
Now your foreach loop should work properly.
Here is a bit more explanation, if what you've seen so far doesn't make sense. When you do this:
$info = array();
while($get_info = mysql_fetch_array($info_result)) {
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
You are overwriting $info with each iteration of the while loop. So at the end of your loop, $info will only contain the last row of your query result.
This explains the result you see:
Array ( [team_id] => 26 [team_points] => 100 )
So when you iterate this array with
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
$info_mation will contain 26, and then 100, which are indeed invalid for foreach.
You need to create a multidimensional array rather than a one-dimensional array. You can do that by modifying your while loop slightly:
while($get_info= mysql_fetch_array($info_result)) {
$info[] = $get_info;
}
Doing it this way adds a new array element to the $info array with each iteration, rather than overwriting the same two elements repeatedly.
this is your code:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
change it to this:
$info = array();
while($get_info= mysql_fetch_array($info_result)){
$info[] = array(
'team_id' => $get_info['team_id'],
'team_points' => $get_info['team_points']
);
}
so, your $info variable contains all the array from the sql result you made.
foreach($info as $inf) {
echo $inf['team_id'];
echo $inf['team_points'];
echo '<br>';
}
and we're done! :)
I am fetching data from my DB and they look like this:
[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]
where the key-1 are the name of the column. (I only have one entry so).
I want to extract only the column values and save them into a new array that will output like this:
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
I want it to look exactly like this and not : [{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}]
I tried this:
$cart["key-1"]=$output["key-1"];
where $output is the outcome of the DB that shown first (the one with []).
and the $cart is the new array I want.
Both are declared as:
$cart=array();
$output=array();
and $output[]=$row where row is the result of the DB fetch. How to do it?
Here's one way to do it, I've substituted the database row for a string here, and made use of json_decode() and json_encode()
$data = '[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]';
// convert to an array
$data = json_decode($data, true);
// create new array here
$cart = array();
for ($i = 0; $i < count($data); $i++)
{
foreach ($data[$i] as $k => $v)
{
if (strpos($k, 'key') !== FALSE)
{
$cart[$k] = $v;
}
}
}
echo $cart['key-1'] . '<br/>';
echo json_encode($cart);
Output:
1
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
This is a very chaotically asked question.
From what I gathered you want maybe this..?
$cart=array();
foreach ($output as $index=>$value){
if stripos($index,"key-"){
cart[$index]=$value;
}
}
Use mysql_fetch_assoc() to get only column names ;)
while ($row = mysql_fetch_assoc($result_of_query))
{
echo $row['key-1'];
echo $row['key-2'];
}
How do I form a multidimensional array using MySQL data? I'm using this code right now:
while($row = mysql_fetch_assoc($result)){
$music[$row['artist']][$row['title']][$row['id']][$row['category_id']] = $row['key'];
}
And I think it would be much easier to use a multi-dimensional array to store my data (artist array => title array => id, category_id, key) but I have no idea how to form one using data from a database. I've googled and can only find examples of static/local data multidimensional arrays, which is no good to me.
I'd also like to know how to output multidimensional data in php for real-world use. Would I use loops? Or would there be an another way?
And I'd just like to say thanks for all the help I've gotten so far at stackoverflow, it's saved me a great deal of headaches!
$music = array();
while($row = mysql_fetch_assoc($result)){
if ( !isset($music[$row['artist']] ) {
$music[$row['artist']] = array()
}
$music[$row['artist']][$row['title']]=array('id'=>$row['id'],'category_id'=>$row['category_id'],'key'=>$row['key'];
}
or more simply if memory requirement is not terribly important (I do this mostly):
$music = array();
while($row = mysql_fetch_assoc($result)){
if ( !isset($music[$row['artist']] ) {
$music[$row['artist']] = array()
}
$music[$row['artist']][$row['title']]=$row;
}
Using two for-as loops would work -- assuming you want to display a tree of artists, than subtrees of titles:
foreach ( $music as $artist => $titles ) {
foreach ( $titles as $title => $details ) {
// do stuff, $details contains all the details for the specific $artist and $title
}
}
var $music = array()
while($row = mysql_fetch_assoc($result))
{
foreach($row as $k => $v)
{
$music[$key][] = $v;
}
}
print_r($music);
I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}
You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.
You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.
Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}
How can I add key value pairs to an array?
This won't work:
public function getCategorieenAsArray(){
$catList = array();
$query = "SELECT DISTINCT datasource_id, title FROM table";
if ($rs=C_DB::fetchRecordset($query)) {
while ($row=C_DB::fetchRow($rs)) {
if(!empty($row["title"])){
array_push($catList, $row["datasource_id"] ."=>". $row["title"] );
}
}
}
return($catList);
}
Because it gives me:
Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )
And I expect:
Array ( [1] =>Categorie 1 [5] => Categorie 2 )
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = 'joy#cargomar.org';
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"] is the key for where the value of $row["title"] is stored in.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge function in loop to combine the each new $new_row array.
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}