Jim
Jim

Reputation:

php arrays. How to format for my result

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

}

Upvotes: 0

Views: 318

Answers (6)

Jim
Jim

Reputation:

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!

Upvotes: 0

Kalium
Kalium

Reputation: 4682

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

Upvotes: 1

strager
strager

Reputation: 90012

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

Upvotes: 0

jerebear
jerebear

Reputation: 6655

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.

Upvotes: 1

Sam
Sam

Reputation: 797

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
}

Upvotes: 0

Paige Ruten
Paige Ruten

Reputation: 176645

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

Upvotes: 3

Related Questions