3

There are very many topics which touch upon obtaining different values from a DB but I think none quite takes this specific case into consideration. I can't find anything which answers these keywords, so perhaps an explanation of the issue will have more success.

I have a table much like this one:

    | ID   | Name   | Location   | Color   | ...
    ============================================
    | 1    | Apple  | Cupboard   | Red     |
    | 2    | Banana | Fridge     | Yellow  |
    | 3    | Lemon  | Fridge     | Yellow  |
    | 4    | Kiwi   | Drawer     | Green   |
    | 5    | Orange | Basket     | Orange  |
    | 6    | Peach  | Drawer     | Orange  |
    | 7    | Grapes | Fridge     | Purple  |
    | 8    | Lime   | Basket     | Green   |

As can be seen, there are several fruit values ordered just the way they were input to the DB. So their ID's won't help us much, as they promise no true organization of the fruits and their info.

What I'm doing is bringing them out of the DB according to location. All is well to this point. However, it's not as easy as that. I'm using jQuery Masonry to distribute my data blocks across the page, and I want the visitor to be able to view samples of fruits in each location intercalated one with the other.

Let's imagine this table had 100+ items. If I just order them alphabetically according to location, for example, an average viewer will get bored and run off before he or she gets to those items in the "Fridge" location, for instance. So I really need to intercalate these values.

Now, I've attempted this at the level of the MySQL query but there doesn't seem to be any SELECT code that allows for intercalation. Now I'm thinking that if I extract all values from each location and set them each within a separate array I can then perhaps unite rows with the same # and put them one after the other.

For instance, I get Array A with Orange and Lime, then Array B with Apple, then Array C with Kiwi and Peach, and then Array D with Banana, Lemon, and Grapes. So Orange, Apple, Kiwi, and Banana will all be 1 in their respective arrays. Somehow, I could perhaps call all 1s and put them side by side so that it prints our 4 data blocks, each with all the info that belongs to each of these fruits in all respective rows 1. Then, I could do the same for all respective rows 2, 3, etc., etc.

However, I'm stuck at this point. I've tried coming up with a couple of codes to do this but I get to the point where I have all individual locations queried from MySQL, then set to individual arrays and, then, separated into individual sub-arrays... but how do I "pair up" these individual arrays by number?

I'm not sure if this has been the clearest explanation possible... Sorry about that. But I do hope you'll understand and somebody might be able to give me a hand.

Perhaps, in lieu of more clarity on the explanation side, I can show you what I would like to obtain at the end of all this, which is all values intercalated by location (ordered ASC with the exception of "Cupboard", which will come first of all) and sub-ordered by ID DESC:

Hum! Doesn't let me post images yet! I need 2 more rep points for that! Oh well, here you have a link to the image.

EDIT: Never mind! Yay! Got the rep points I needed to post an image. Thanks!

enter image description here

5
  • 1
    You keep using that word, I do not think it means what you think it means.
    – ultranaut
    Mar 9, 2013 at 3:23
  • @ultranaut - Listen, all you have to do is intercalate between the lines and his meaning will be clear.
    – anon
    Mar 9, 2013 at 3:30
  • Intercalate? May not be of popular use, ultranaut, but to intercalate is to interpolate or interpose. As interpose you'll find it suits my query quite adequately. As interpolate it fits anon's ironic remark. Mar 9, 2013 at 3:38
  • At any rate, I hope the question is understood regardless of my choice in terminology. Mar 9, 2013 at 3:39
  • Hey, it's not that often that you get a legit chance to use that line; when it presents itself you take it. While I might have chosen a different word, your question's fine.
    – ultranaut
    Mar 9, 2013 at 4:45

2 Answers 2

2

Get the values from the DB and put them in an array where you set the location as key. You can iterate through the location/keys then and pick one item per location/key with array_shift():

<?php

$set['cupboard'] = array('apple');
$set['basket'] = array('orange', 'lime');
$set['drawer'] = array('kiwi', 'peach');
$set['fridge'] = array('banana', 'lemon', 'grapes');

$locations = array_keys($set);

$found=true;
while($found) { //as long as there are fruits in at least one array
    $found = false;
    foreach($locations as $row) { //go through all arrays
        $fruit = array_shift($set[$row]); //get the first fruit of the array and delete it from the array
        if(isset($fruit)) { //there is a fruit
            $finalArr[] = $fruit." ($row)"; //add the fruit to the final array
            $found = true; //I found a fruit so keep going
        }
    }
}

var_dump($finalArr);
//Output array(8) { [0]=> string(16) "apple (cupboard)" [1]=> string(15) "orange (basket)" [2]=> string(13) "kiwi (drawer)" [3]=> string(15) "banana (fridge)" [4]=> string(13) "lime (basket)" [5]=> string(14) "peach (drawer)" [6]=> string(14) "lemon (fridge)" [7]=> string(15) "grapes (fridge)" }
?>

Hope this helps.

EDIT: Here a version, which works with whole DB-rows

<?php

$dbresult = mysqli_query($dblink, 'SELECT * FROM yourtable');
while ($dbrow = mysqli_fetch_array($dbresult, MYSQLI_ASSOC)) {
    $set[$dbrow['Location']][] = $dbrow;
}

$locations = array_keys($set);

$found=true;
while($found) { //as long as there are fruits in at least one array
    $found = false;
    foreach($locations as $row) { //go through all arrays
        $fruitArr = array_shift($set[$row]); //get the first fruit of the array and delete it from the array
        if(isset($fruitArr)) { //there is a fruit
            $finalArr[] = $fruitArr; //add the whole fruit-array (= row from DB) to the final array
            $found = true; //I found a fruit so keep going
        }
    }
}
4
  • Hey, Thorsten! Thousand thanks! As it is, it's working great! However, I can't get it to work handling arrays I've pre-built during the DB querying process. I keep getting: [0]=> string(13) "Array (cupboard)" [1]=> string(13) "Array (basket)" [2]=> string(13) "Array (drawer)" [3]=> string(13) "Array (fridge)" [3]=> string(13) "Array (basket)" . . .. I'm thinking it's something I need to put up where I'm setting the arrays for each location key, i.e.: $set['basket'] = $basket_items;. I've tried a couple of things but it doesn't work. How would I need to handle the $basket_items var? Mar 9, 2013 at 18:01
  • Or, another thought: how should I handle, on the other end of you code, each individual sub-array I'm getting from it? (P.S. This has, as it is, surely been very helpful!) Mar 9, 2013 at 18:03
  • O.K.! I think I've solved it. I'll clean it up and post it here if works out fine! Again, a million thanks, Thorsten! Mar 9, 2013 at 18:53
  • Good to hear that it works. I added a new version, which stores the whole fruit-array (= 1 row) instead the name only. Feel free to use or to ignore it :).
    – Thorsten
    Mar 10, 2013 at 4:28
0

My final code based on the code Thorsten was so kind as to work out.

Thorsten's code worked perfectly for the arrays built at its beginning. Thanks a lot Thorsten!

I needed to handle pre-built arrays that were output from my MySQL DB handler code. So I had to work a couple of small changes on Thorsten's code and now it works for my specific needs.

Here you have my final code. Thorsten's original code is in his/her response at the bottom.

Hope it may help others out there!

    <?php

    /* The vars below come from the MySQL DB handler. */
    $set['cupboard'] = $fruits_in_cupboard;
    $set['basket'] = $fruits_in_basket;
    $set['drawer'] = $fruits_in_drawer;
    $set['fridge'] = $fruits_in_fridge;

    $locations = array_keys($set);

    $found=true;
    while($found) { //as long as there are fruits in at least one array
        $found = false;
        foreach($locations as $row) { //go through all arrays
            $fruit = array_shift($set[$row]); //get the first fruit of the array and delete it from the array

            /* Here I include a code to handle every var passed
               through each $fruit sub-array. */
            include('inc/fruity-builder.inc');

            if(isset($fruit)) { //there is a fruit
                /* Here I make a final array out of all $item values. */
                $finalArr[] = array('id'=>$id,'name'=>$name,'location'=>$location,'color'=>$color); //get the first fruit of the array and delete it from the array
                $found = true; //I found a fruit so keep going
            }
        }
    }

    foreach($finalArr as $fruit):

    ?>

    <!-- This is just in order to output our data for each item
         and will surely change according to specific needs. It is
         setup here as an example, following the example I gave
         in the image I posted (above). -->
    <div>
        <h2><?php $fruit['fruit_name'] ?></h2>
        <p>is <?php $fruit['fruit_color'] ?><br />
           and in <?php $fruit['fruit_location'] ?></p>
    </div>

    <?php

    endforeach;

    ?>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.