简体   繁体   English

PHP - 从对象数组中按对象属性获取条目

[英]PHP - get entry by object property from an array of objects

The array function looks like this数组函数看起来像这样

function searchArray($array, $key, $value){
    $array_iteration = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

    $output = array();

    foreach($array_iteration as $sub_array){
        $sub = $array_iteration->getSubIterator();
        if($sub[$key] == $value){
            $output[] = iterator_to_array($sub);
        }
    }

    return $output;
}

I have variables which are passed to the cart script like $color, $size, $product_id .我有传递给购物车脚本的变量,如$color, $size, $product_id In the array I am trying to sum amount base on product_id, color and size but it was only summing all product with the same color irrespective of the product_id instead of categorizing by product_id , color**** and **size在数组中,我试图根据product_id、colorsize求和数量但它只是将所有具有相同颜色的产品相加而不考虑product_id而不是按product_idcolor**** 和 **size 进行分类

How can I get color, size and product_id in searchArray() ?如何在searchArray()获取颜色、大小和 product_id ?

What's wrong with the logic?逻辑有什么问题?

Here is the cart.php这是cart.php

if($_POST['cat_type'] == "single"){
$color           = $_POST['color'];
$product_size    = str_replace("+", " ", $_POST['product_size']);
$amount           = $_POST['sprice'];
$vendor          = $_POST['sseller'];
//$quantity        = $_POST['quantity'];
$product_id      = (int)$_POST['product_id'];
$img             = "";
$cat             = $_POST['cat_type'];


$product_info = $product->getProductById($product_id);
$title =  $product_info[0]->title;

$cart = array();


if(isset($_SESSION['__cart'])){
        $cart  = $_SESSION['__cart'];
}

$current_item = array();
$current_item['image'] = $product_info[0]->images;
$current_item['pimage'] = $img;
$current_item['title'] = $product_info[0]->title;
$current_item['price'] = $amount;
$current_item['id'] = $product_info[0]->id;
$current_item['vendor'] = $vendor;
$current_item['color'] = $color;
$current_item['size'] = $product_size;
$current_item['name'] = $title;
$current_item['category'] = $cat;
$qty = 1;

if (isset($_POST['quantity'])) {
        $qty = $_POST['quantity'];
}

    if(!empty($cart)){
        $search_result = searchArray($cart, 'color', $color, 'size', $product_size, 'id', $product_id);

        $index = 0;
        if($search_result){
            foreach($cart as $key=>$value){
                if($value['color'] == $color && $value['size'] == $product_size && $value['id'] == $product_id){
                    $index = $key;
                    break;
                }
            }


            $cart[$index]['quantity'] += $qty;
            $cart[$index]['amount'] += $amount*$qty;
            } else {
            $current_item['amount'] = $amount*$qty;
            $current_item['quantity'] = $qty;

            $cart[] = $current_item;
        }
    } else {
        $current_item['amount'] = $amount*$qty;
        $current_item['quantity'] = $qty;

        $cart[] = $current_item;
    }

    $_SESSION['__cart'] = $cart;
    echo "1";
    exit;

}

First, I want to thank every contributors to this forum.首先,我要感谢本论坛的每一位贡献者。 Your time, patient and teaching as made people like me learned over the years.你的时间、耐心和教导让像我这样的人多年来学到了东西。

Back to the answer for my question above:回到我上面问题的答案:

For someone who might be in the same situation, this is how I solved it.对于可能处于相同情况的人,这就是我解决的方法。

In a multidimensional array, if there is no unique pair of key => value (more than one pair of key => value) exists then in that case if we search the element by a single key => value pair then it can return more than one items.在多维数组中,如果不存在唯一的键 => 值对(超过一对键 => 值),那么在这种情况下,如果我们通过单个键 => 值对搜索元素,则它可以返回更多比一项。 Therefore we can implement the search with more than one key => value pair to get unique items.因此,我们可以使用多个键 => 值对来实现搜索以获取唯一项。

Approach: For each array inside the array, iterate over the search array and if any search key value doesn't match with corresponding array key value we discard that array and continue the process for next array.方法:对于数组中的每个数组,遍历搜索数组,如果任何搜索键值与对应的数组键值不匹配,我们丢弃该数组并继续下一个数组的过程。

Suppose we want to search product details from a list of the products which contains product of different section, therefore, in this case, product_id alone might not give the correct output.假设我们要从包含不同部分产品的产品列表中搜索产品详细信息,因此,在这种情况下,单独的product_id可能无法提供正确的输出。 So we will need to search the list with more key => value that is product_id , color and size .因此,我们需要使用更多的键 => 值(product_idcolorsize )来搜索列表。

 function searchArray($array, $search_list) { 

        // Create the result array 
        $result = array(); 

        // Iterate over each array element 
        foreach ($array as $key => $value) { 

            // Iterate over each search condition 
            foreach ($search_list as $k => $v) { 

                // If the array element does not meet 
                // the search condition then continue 
                // to the next element 
                if (!isset($value[$k]) || $value[$k] != $v) 
                { 

                    // Skip two loops 
                    continue 2; 
                } 
            } 

            // Append array element's key to the 
            //result array 
            $result[] = $value; 
        } 

        // Return result  
        return $result; 
    } 

Passing the values and iterating传递值并迭代

if($_POST['cat_type'] == "single"){
$color           = $_POST['color'];
$product_size    = str_replace("+", " ", $_POST['product_size']);
$amount           = $_POST['sprice'];
$vendor          = $_POST['sseller'];
//$quantity        = $_POST['quantity'];
$product_id      = (int)$_POST['product_id'];
$img             = "";
$cat             = $_POST['cat_type'];


$product_info = $product->getProductById($product_id);
$title =  $product_info[0]->title;

$cart = array();


    if(isset($_SESSION['__cart'])){
            $cart  = $_SESSION['__cart'];
    }

    $current_item = array();
    $current_item['image'] = $product_info[0]->images;
    $current_item['pimage'] = $img;
    $current_item['title'] = $product_info[0]->title;
    $current_item['price'] = $amount;
    $current_item['id'] = $product_id;
    $current_item['vendor'] = $vendor;
    $current_item['color'] = $color;
    $current_item['size'] = $product_size;
    $current_item['name'] = $title;
    $current_item['category'] = $cat;



    $qty = 1;

    // Define search list with multiple key=>value pair 
    $search_items = array('color'=>$color, 'size'=>$product_size,  'id'=>$product_id); 

    if (isset($_POST['quantity'])) {
            $qty = $_POST['quantity'];
    }

        if(!empty($cart)){
                // Call search and pass the array and 
          // the search list 
         $search_result = searchArray($cart, $search_items); 

            $index = 0;
            if($search_result){
                foreach($cart as $key=>$value){
                    //var_dump($value);
                    if($value['color'] == $color and $value['size'] == $product_size and $value['id'] == $product_id){
                        $index = $key;
                        break;
                    }
                }


                $cart[$index]['quantity'] += $qty;
                $cart[$index]['amount'] += $amount*$qty;
                } else {
                $current_item['amount'] = $amount*$qty;
                $current_item['quantity'] = $qty;

                $cart[] = $current_item;
            }
        } else {
            $current_item['amount'] = $amount*$qty;
            $current_item['quantity'] = $qty;

            $cart[] = $current_item;
        }

        $_SESSION['__cart'] = $cart;
        echo "1";
        exit;

    }

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

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