tags:

views:

168

answers:

6

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

}
+3  A: 

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).

yjerem
The only issue with that is that the entire app depends on the database wrapper. I can't change it now. It is in a class and that is basically all I have. Is there no way to get this based on a fetch_assoc?
Yes, you are right, I don't want the numeric indexes.
A: 

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
}
Sam
Is there a way to do this with a foreach instead of a while loop?
sure. mysql_num_rows($query) will tell you how many rows it returned... but you still have to call mysql_fetch_array/assoc every iteration.
Mark
+1  A: 

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.

jerebear
Thanks for the hand.. The db is mysql. The code sample that I was given uses mysql_fetch_array and NOT assoc and I am bewildered as to how it works for the code given to me but yet not for my own code. I can't see what the difference is.
fetch_array returns both index as numeric and index as field name. fetch_assoc returns only index as field name.
jerebear
Ah, thanks.. That makes sense, hence "BOTH". Is there a different syntax to switch between the two?
+1  A: 

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";
    }
}
Kalium
Yes sir.. That outputs the correct vals. Here is what I now get.Array ( [id] => 1 [cust] => bobs auto )Can you please tell me what I have going on that I have to use your code to get the correct results?
@Jim, what? I thought the array you posted in your comment is what you expected. It isn't, then? What should it be?
strager
I think you're getting the result of a `mysql_fetch_array()` call without the second parameter set (or set to MYSQL_BOTH). The result is that you get both associative and numeric elements shoveled in.
Kalium
Yes, exactly. The result that I posted in THIS comment section is closer to what I need. What I posted in the original comments was what I was getting back from the database class. BTW The db class uses mysql_fetch_assoc then i++ and is then passed as an array. Maybe that helps? Thanks for the help!
I have the db method. Shere should I post it? Here or back up in the original spot where I stated my question? Maybe this will shed light on the issue.
Please post it back up at the top. That sort of thing is very helpful.
Kalium
Ok, great, will do. ALso.. your code was close but not close enough. I'll explain above. Thanks for the hand!
OK, I see now. Something as simple as `$out[$array['id']] = $array['cust'];` should do the transform you want, although that's no kind of general solution.
Kalium
OK, let me give that a try and I will be right back. Also.. Would you mind please explaining that bit of code you just posted? I have seen it used with my db class before but don't understand how it works. OK, brb
@Jim, My answer (which I posted before I read @Kalium's comment (sorry if I looks like I stole your idea =X)) shows how you'd do this.
strager
That snippet puts an element into a new array, using a key of the value at index 'id' in $array variable, and sets the value in the new array to the value at index 'cust' in $array.
Kalium
Kalium, Thanks for that explanation. Its not that easy to understand though. I think that after I finish this application, I will need to go back and rewrite some of the methods for the db wrapper.
Your code really helped me Kalium. Thanks!!
A: 
$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.

strager
Hey Strager.. The json_encode() is in a JQuery script already. All I have to do is get my data into an array and then I'm golden but this has really turned out to be a small nightmare.
@Jim, See my comments to your original answer. Also, why would json_encode be on the jQuery side?? If that's the case you're not transporting using JSON at all!
strager
You'll have to forgive me. I'm no js or JQuery expert. I'm really trying to learn more of it. It plugin off of the JQ site. All I know is that with the data in this array, the rest is taken care of because my textbox populates with the data.
Ok, your right. Your snippet of $ret[$row['id']] = $row['cust']; is almost working. I am missing the index column though. I need the key=>val pair togther. I'm only getting the val.
@Jim, Can you post what you are given (input) exactly as it is given (using print_r) and your expected results (output) exactly as outputted with print_r in your original question? This would help tremendously.
strager
Strager, Kalium's code worked perfectly. I got it to work and formats beautifully. Is there a trick to understanding these arrays? They have always been hard for me to understand.
@Jim, This may help: http://us3.php.net/manual/en/language.types.array.php
strager
Strager, Thanks a million. I am still having an issue though with strpos in the foreach loop. Would you mind having a look?
A: 

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!