Jump to content

query into multidimensional array


turpentyne

Recommended Posts

I'm trying to find a good simple tutorial on how to take my query and turn it into a multidimensional array, but can't seem to find anything.

 

basically I have this:

 


?php 
include("../builder-test-code/dbc.php");


$query_options  = "SELECT component_name, image_filepath, component_category FROM tbl_components";
$result = mysql_query($query_options);

while($row = mysql_fetch_assoc($result)){

$categorized_items = array();
// something remotely like this?
$categorized_items[$row['component_category']] = array($row['component_name'], $row['image_filepath']);


}

?>

 

basically I am pulling all the results from a table with these three rows, and I'm trying to group them into individual arrays by the column "component_category" so I can figure out how to print the results of each array out to the page.

Link to comment
Share on other sites

Why not just ORDER BY component_category in your query?

 

To answer your question, you may want this

 

$categorized_items[$row['component_category']][] = array($row['component_name'], $row['image_filepath']);

 

The extra [] on the end will 'push' the data in to a new key of the array.

Link to comment
Share on other sites

Nope, it won't.

for ($run = 0; $run < 10; $run++) {
    $arr['test'][] = array ($run);
}
var_dump ($arr);
/* Result:
array(1) {
  ["test"]=>
  array(10) {
    [0]=>
    array(1) {
      [0]=>
      int(0)
    }
    [1]=>
    array(1) {
      [0]=>
      int(1)
    }
    [2]=>
    array(1) {
      [0]=>
      int(2)
    }
    [3]=>
    array(1) {
      [0]=>
      int(3)
    }
    [4]=>
    array(1) {
      [0]=>
      int(4)
    }
    [5]=>
    array(1) {
      [0]=>
      int(5)
    }
    [6]=>
    array(1) {
      [0]=>
      int(6)
    }
    [7]=>
    array(1) {
      [0]=>
      int(7)
    }
    [8]=>
    array(1) {
      [0]=>
      int(
    }
    [9]=>
    array(1) {
      [0]=>
      int(9)
    }
  }
}
*/

That said, it is a very good practise to do so anyway. Cuts down on the number of warnings, and avoids potential problems. ;)

Link to comment
Share on other sites

$query  = "SELECT component_name, image_filepath, component_category
           FROM tbl_components";
$result = mysql_query($query);

$categorized_items = array();
while($row = mysql_fetch_assoc($result))
{
    $category = array_pop($row);
    $categorized_items[$category][] = $row;
}

Link to comment
Share on other sites

haha! Now my head is spinning from the replies! :)

 

I've gotten to here, but now I'm not sure how/where I echo a header for each nested array, when I'm printing to the page?

 

$categorized_items = array();

$query_options  = "SELECT component_name, image_filepath, component_category FROM tbl_components";
$result = mysql_query($query_options);

while($row = mysql_fetch_assoc($result)){
$categorized_items[$row['component_category']][] = array($row['component_name'], $row['image_filepath']);
}

function PrintArray($categorized_items)
{

if(is_array($categorized_items))
{

	foreach($categorized_items as $key=>$value)
	{

		if(is_array($value))
		{

		PrintArray($value);

		}
		else
		{

		echo " $key: $value<br>";
		}
	}
}
}  

?>

<!--html -->
<?php
echo "and now...<br>";
PrintArray($categorized_items);

?>


Link to comment
Share on other sites

Why dump the results into an array only to use the array for output. Just create the output from the query results.

 

$query  = "SELECT component_name, image_filepath, component_category
           FROM tbl_components
           ORDER BY component_category";
$result = mysql_query($query);

$category = false;
while($row = mysql_fetch_assoc($result))
{
    if($category != $row['component_category'])
    {
        $category = $row['component_category'];
        echo "<br>{$category}<br>\n";
    }
    echo "{$row['component_name']} <img src='{$row['image_filepath']}'><br>\n";
}

Link to comment
Share on other sites

I was told by someone that they felt the best way to generate a list with headers was to put them in a multidimensional array and then loop through it to create something like this. They mentioned the other way that Xyph suggested at the start of this thread (and that you just suggested), but said the array method was better in their mind.

 

CATEGORY 1

item 1

item 2

item 3

 

CATEGORY 2

item 4

item 5

item 6

 

and so on... Is this not a good way to do this? maybe I'm taking the long way around? Or are there benefits you can think of?

 

right now, it's printing everything to the page, but not breaking it apart.

 

Link to comment
Share on other sites

If you know the structure of the array, and that it always the same number of elements in the second dimension, then you're far better off skipping that second loop.

 

Also, unless you need to use the data in another location, you don't need to save it in an interim array either. It's just a waste of time and memory.

 

I'd do something like what Psycho posted above, if I were you. Only saving the completed table to a variable, instead of printing it outright.

Link to comment
Share on other sites

Well, that was certainly easier...

 

quick follow-up question and I'll call this thread solved.

 

what about a footer? I've got a header , but I also need a footer, and didn't think about that...

 

Is there some similar method to the header snippet that can be used to detect when to put a bit of code before going on to the next grouping?

 

 

Link to comment
Share on other sites

If you're thinking about a footer for each section, then just print it out before the header for the next. Just remember to save the previous line at the bottom of the loop first, so you can get the necessary data.

Doing it that way means you don't have to detect twice, but can just refer to the previous line's data before starting on a new category.

 

Something like this, in other words:

while ($row = fetch_array ()) {
    if (if($category != $row['component_category'])
    {
        // Add a footer unless this is the first row, and thus the first category.
        if (isset ($prev)) {
            $output .= $prev['footer']."</p>";
        }
        $category = $row['component_category'];
        $output .= "<p>{$category}<br>\n";
    }
    $output .= "{$row['component_name']} <img src='{$row['image_filepath']}'><br>\n";
    $prev = $row;
}

Simple and easy. ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.