简体   繁体   中英

PHP - Search for a value in Multi-Dimensional array and returns its ID

I'm practicing php by creating a clothing shop.

Consider my PHP Database array:

$mens[101] = [
    "title" => "Block Original T-Shirt",
    "img" => "img/clothing/men/tShirts/block-orig-black.jpg",
    "price" => 16,
    "color" => "black",
    "altColor" => array("black" , "white", "grey"),
    "size" => array (
        array(
            "size" => "x-small",
            "qty" => 3
        ),
        array(
            "size" => "small",
            "qty" => 10
        ),
        array(
            "size" => "medium",
            "qty" => 0
        ),
        array(
            "size" => "large",
            "qty" => 15
        ),
        array(
            "size" => "x-large",
            "qty" => 9
        )
    ),
    "description" => "Duis eget volutpat mauris, quis lacinia orci. Cras mattis bibendum lorem, nec faucibus ipsum fermentum at. Nulla tincidunt ligula suscipit elit tincidunt, non vulputate nibh dapibus. Proin quis sapien hendrerit, vulputate nibh sit amet, rutrum quam.",
    "category" => "m-tShirts"
];

$mens[102] = [ ....]
$mens[103] = [ ....]
$mens[...

A newbie question granted, but I'm looping through the database looking for those items with category = "m-shirts", once I have found these I would like to pick one random item to work with from those results.

foreach($mens as $sug) {
    if ($sug["category"] === "m-shirts") {
        echo key($mens);
    }
}

I'm using echo to check if the correct ID's are being collected. However this echos "101" 15 times (the amount of products that have the category "m-shirts"). But I want the unique ID for those particular results ( coincidentally are ID's 201 through 215). In english I want to:

foreach(product in $mens array){
     if(product has the category "m-shirts"){
           collect the id's;
           select a random id and store as variable $suggestion
     }
}

If anyone can help me or point me in the direction of any articles/tutorials. I've spent most my afternoon going through the php docs and have also worked through the Learning PHP, MySQL and JavaSript (by Robin Nixon) chapter on arrays without being able to work this out.

Thanks In advance!

Instead of rolling your own filter, use PHP's: array_filter .

$mTShirts = array_filter($mens, function($item) {
        return $item['category'] == 'm-tShirts';
    });

With that, you can access the results in whichever way you need, including foreach or via some collection-oriented method, such as the array functions or iterators . In this case, array_rand can be used to pick a random array element.

$idx = array_rand($mTShirts);
$item = $mens[$idx];

The manual should be your first stop before writing an operation. The SPL in particular has many useful classes & functions, but don't neglect the entire function reference (no longer an accurate name, as there are many classes listed; "extension interface reference" is more accurate).

However, this begs the question of whether to implement a datastore in PHP or use an external DB, which already has safe, efficient implementations for standard operations. Anything you write is liable to:

  1. be less efficient,
  2. be buggier,
  3. have fewer features,
  4. take valuable development time to design and implement

You can simply loop through the Array of Shop-Items like you did in your first Foreach Loop. Then create an Array to hold the IDs Products that belong to the "m-shirts" Category. Within the Loop, you can just simply push all the IDs of such Products to the created Array Variable. Afterwards, you can generate a Random Number between 0 and the Length of the Array of IDs minus One. Using this Random number, you can pick out an ID....

    <?php

        // CREATE AN ARRAY TO HOLD THE IDS OF PRODUCTS UNDER THE CATEGORY: m-shirts     
        $mShirtsCatIDS  = array();

        // LOOP THROUGH THE SHOP ITEMS IN SEARCH OF PRODUCTS WITH CATEGORY: m-shirts
        foreach($mens as $id=>$men){
            // IF FOUND, PUSH THE ID TO THE $mShirtsCatIDS ARRAY
            if($men['category'] == 'm-shirts'){
                // PUSH THE IDs TO THE $mShirtsCatIDS ARRAY
                $mShirtsCatIDS[]    = $id;
            }
        }

        // IF OUR ARRAY OF IDs IS NOT EMPTY; JUST GENERATE A RANDOM NUMBER
        // BETWEEN 0 AND THE LENGTH OF THE ARRAY MINUS 1.
        // USING THAT GENERATED RANDOM NUMBER, PICK OUT ONE ID...       
        if(count($mShirtsCatIDS)>0){
            // GENERATE THE RANDOM NUMBER...
            $randNum    = rand(0, (count($mShirtsCatIDS) - 1));

            // PICK OUT AN ID, USING THIS RANDOM NUMBER...
            $randID     = $mShirtsCatIDS[$randNum];
            // END OF STORY..... ;-) 
        }

        var_dump($randID); //<== DUMPS A NEW ID EACH TIME.

        // YOU CAN NOW GET THE PRODUCT CORRESPONDING TO THIS ID
        // LIKE SO: $mens[$randID].... 

Check out a simulated Demo HERE .

Hope you find this here any helpful.

Cheers & Good Luck....

As @firstone mentioned, I think the answer to your specific question is to use:

$results = [];
foreach($mens as $key => $value) {
    if ($value["category"] === "m-shirts") {
        $results[] = $key;
    }
}

# view all results: // print_r($results);

// get random key from results:
$rand_item = array_rand($results);

echo $results[$rand_item];

If all you want is a random array that has category m-shirts then I would do:

shuffle($mens);
$cats   = array_column($mens, null, 'category');
$result = $cats['m-shirts'];
  • Shuffle the array (randomize)
  • Get array indexed with category (there will be only one per category since they must be unique indexes)
  • Use the array with index m-shirts

Or shorter:

shuffle($mens);
$result = array_column($mens, null, 'category')['m-shirts'];

Try php array_search function. For more information please check this url: function.array-search

Establish an array above the foreach to collect the results of the iteration.

Use the middle block of code provided; but change it a little bit. It looks like you've got an array in an array, but only a single layered iteration and inspection in the if test. Either lay in another round of iterations to cover the next layer of array keys, or change the if test to go after that one key you want specifically. A var_dump in that area can help you debug and develop that part better.

That is, it will be hard to reach up, into an abstract layer of naming above what's used to describe the outermost loop of the iterations.

In the brackets after passing the if test, add the "id" value to the holding array. In this way, you can collect all of the ids discovered. If the id is in a variable called key, then just add that in like:

$holder[] = $key;

or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM