Multidimensional arrays in PHP

How to add elements to a multidimensional array? I basically make an application that calculates what people buy at the supermarket and how much it is.

Sue buys 2 baths with oil and 1. Toothpaste

John buys 1 peach and 1 banana.

I think the array will look something like this.

$sue[butter] = array(); 
$sue[butter][] = 2;
$sue[toothpaste] = array(); 
$sue[toothpaste][] = 1;
$john[peach] = array(); 
$john[peach][] = 1;
$john[banana] = array(); 
$john[banana][] = 1;

My current code can only write an element and the number of elements.

public $items = array();

public function AddItem($product_id)
{
    if (array_key_exists($product_id , $this->items))
    {
        $this->items[$product_id] = $this ->items[$product_id] + 1;
    } else {
        $this->items[$product_id] = 1;
    }
}

I just don't know how to put this inside an array for each person.

Thanks!

+3
source share
4 answers

Instead, it might be easier for you to encapsulate in a class. For example, for each person to be a class, and then give them attributes.

Once you get into multidimensional arrays, it will be harder for you to maintain your code.

( ):

class Customer {
    //this is an array of FoodItem objects.
    private $foodItems[];

    // any other methods needed for access here
}

class FoodItem {
    //could be a String, or whatever it needs to be
    private $itemType;

    //the number of that item purchased
    private $numPurchased;
}
+4

Hm, , ?

$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;

$john = array();
$john['peach'] = 1;
$john['banana'] = 1;

, , , .

+3

, :

$sue[butter] = array(); 
$sue[butter][] = 2;

I think something like this will work:

$customers[sue][butter] = 2; 
$customers[sue][toothpaste] = 1; 
$customers[john][peach] = 1; 
$customers[john][banana] = 1;

This way you create an array of customer names. Then in each array of customers you have an array of your products. Each product then contains the product number that the customer bought.

+1
source
$data = array();
$data["persons"] = array("Sue","John");
$data["articles"] = array("butter","toothpaste","peach","banana");

$data["carts"] = array();

$data["carts"][0][0] = 2; // sue 2 butter packets
$data["carts"][0][1] = 1; // sue 1 tooth paste

$data["carts"][1][2] = 1; // john peach
$data["carts"][1][3] = 1; // john banana
0
source

Source: https://habr.com/ru/post/1707478/


All Articles