0

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
  • What is '$items'? Is it the original array you printed at the beginning of your post? Commented Apr 2, 2009 at 4:57
  • If that is the case, remove your is_int check and it should work (change id to customer_id and cust to name, of course). Commented Apr 2, 2009 at 4:57
  • Items is the return value from the db class which holds the array. I will try and remove the is_int to see if that works. Thanks. Commented Apr 2, 2009 at 5:17

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?
1

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

12 Comments

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?
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.
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.
|
1

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.

3 Comments

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.
Ah, thanks.. That makes sense, hence "BOTH". Is there a different syntax to switch between the two?
0

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
}

2 Comments

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.
0
$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.

7 Comments

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!
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.
|
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.