简体   繁体   中英

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 . 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

How can I get color, size and product_id in searchArray() ?

What's wrong with the logic?

Here is the 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. So we will need to search the list with more key => value that is product_id , color and size .

 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;

    }

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