简体   繁体   English

PHP-在多维数组中搜索值并返回其ID

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

I'm practicing php by creating a clothing shop. 我正在通过创建服装店来练习php。

Consider my PHP Database array: 考虑我的PHP数据库数组:

$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. 授予了一个新手问题,但我要遍历数据库以查找类别=“ m-shirts”的那些项目,一旦找到这些项目,我想从这些结果中选择一个随机的项目进行处理。

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. 我正在使用echo检查是否收集了正确的ID。 However this echos "101" 15 times (the amount of products that have the category "m-shirts"). 但是,这回显“ 101” 15次(“ m恤”类别的产品数量)。 But I want the unique ID for those particular results ( coincidentally are ID's 201 through 215). 但是我想要这些特定结果的唯一ID(巧合的是ID的201到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. 我花了大部分时间来阅读php文档,并且还无法通过数组学习“学习PHP,MySQL和JavaSript(由Robin Nixon设计)”一章。

Thanks In advance! 提前致谢!

Instead of rolling your own filter, use PHP's: array_filter . 不用滚动自己的过滤器,而是使用PHP的: 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 . 这样一来,您可以使用所需的任何方式访问结果,包括foreach或通过某些面向集合的方法(例如数组函数迭代器)访问结果 In this case, array_rand can be used to pick a random array element. 在这种情况下, array_rand可用于选择随机数组元素。

$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). 特别是SPL具有许多有用的类和函数,但不要忽略整个函数引用 (不再列出确切的名称,因为列出了许多类;“扩展接口引用”更为准确)。

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. 但是,这引出了一个问题,即是以PHP实现数据存储还是使用外部DB(对于标准操作已经具有安全,有效的实现)。 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. 您可以像在第一个Foreach循环中那样简单地遍历Shop-Items数组。 Then create an Array to hold the IDs Products that belong to the "m-shirts" Category. 然后创建一个数组来保存属于“ m恤衫”类别的ID产品。 Within the Loop, you can just simply push all the IDs of such Products to the created Array Variable. 在循环中,您只需将此类产品的所有ID推送到创建的数组变量中即可。 Afterwards, you can generate a Random Number between 0 and the Length of the Array of IDs minus One. 之后,您可以生成一个介于0和ID数组长度减去1之间的随机数。 Using this Random number, you can pick out an ID.... 使用此随机数,您可以选择一个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: 如@firstone所述,我认为您的特定问题的答案是使用:

$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: 如果您想要的只是一个具有类别m-shirts的随机数组,那么我应该这样做:

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) 获取用category索引的数组(每个类别只有一个,因为它们必须是唯一索引)
  • Use the array with index m-shirts 将阵列与索引m-shirts

Or shorter: 或更短:

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

Try php array_search function. 尝试php array_search函数。 For more information please check this url: function.array-search 有关更多信息,请检查以下URL: function.array-search

Establish an array above the foreach to collect the results of the iteration. 在foreach上方建立一个数组,以收集迭代结果。

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. 看起来您在一个数组中有一个数组,但是if测试中只有一个分层的迭代和检查。 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. 要么进行另一轮迭代以覆盖数组键的下一层,要么将if测试更改为您想要的那个键之后。 A var_dump in that area can help you debug and develop that part better. 该区域中的var_dump可帮助您更好地调试和开发该部分。

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. 通过if测试后的方括号中,将“ id”值添加到保持数组中。 In this way, you can collect all of the ids discovered. 这样,您可以收集所有发现的ID。 If the id is in a variable called key, then just add that in like: 如果id在名为key的变量中,则只需将其添加为:

$holder[] = $key;

or similar. 或类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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