Javi Javi - 10 months ago 42
PHP Question

Basic associative arrays in php. How to fill them

First of all, I'm sorry if this is too easy for many of you... I'm learning as much as I can.

I want to create an array with customers, like:

$customers=["customer A", "customer B", "customer C"];


Then, I want to create an array with some characteristics for every customer in that array. The characteristics are 'City', 'Points' and 'Results'. Each customer has a name (string), not a number.

I would need to change (or update) a characteristic ('points') of all customers of the array when needed with PHP. Something like:

for each $customer in $customers {
$points[$customer]=$points[$customer]+2;
}


I would like to also update the info of only one customer, something like:

$points['Customer C']=$points['Customer B']+3;


Finally, I need to access the characteristics of a give Customer, like:

$i=$points['Customer A']+$result['Customer A'];


I know this is not correct, but how should I proceed in PHP?

How could I eliminate a Customer from the array $Customers (with all its characteristics)? And how could I add a new Customer to $Customers?

Thank you very much for your help. I really appreciate it.

Answer Source

As your question states, assoc array:

$customers = [
    'customerA' => [
        'points' => 100,
        'city' => 'New York',
        'results' => 40,
    ],
    'customerB' => [
        'points' => 75,
        'city' => 'Amsterdam',
        'results' => 10,
    ],
    'customerC' => [
        'points' => 25,
        'city' => 'London',
        'results' => 5,
    ],
];

// Remove customer C
unset($customers['customerC']);

// add customer D
$customers['customerD'] = [
    'points' => 50,
    'city' => 'Berlin',
    'results' => 5,
];

// Update points of customer
$customers['customerA']['points'] += 2; // Adds 2 points
// Update points of customer by another customers points
$customers['customerB']['points'] = $customers['customerA']['points'] + 3;

// Add 2 points to each customer
foreach ($customers as $name => $properties) {
    $properties['points'] += 2;
    $customers[$name] = $properties; 
}

The key within the customers array is the name of your customer and all the properties are within the value of that key.