arma
arma

Reputation: 4124

Working with array and unique key in php

How would I generate an array in which I need to use a unique key and assign multiple values not unique to that key in a foreach loop?

Upvotes: 0

Views: 3126

Answers (3)

KingCrunch
KingCrunch

Reputation: 131861

$result = array();
foreach ($values as $value) {
    $uniqueKey = createUniqueKey($value);
    if (!array_key_exists($uniqueKey, $result) {
        $result[$uniqueKey] = array();
    }
    $result[$uniqueKey][] = $value;
}

Its similar to JDs solution: It creates a multidimensional array. Of course you must define a way to map every value to a single unique key (here described as createUniqueKey())

Upvotes: 2

Toby Joiner
Toby Joiner

Reputation: 4376

is this what you are talking about? if not can you give an example of the data?

$unique_keys = (1,2,3,4,5);

foreach ( $unique_keys as $unique_key ) {
    $new_array[$unique_key] = array(3,57,22);
}

Upvotes: 0

Darbio
Darbio

Reputation: 11418

You could use a multidimensional array.

It's been a while since I used PHP, but from memory:

$array[0][0] = "Item 1";
$array[0][1] = "Item 2";
$array[0][2] = "Item 3";
$array[1][0] = "Item 1";
$array[1][1] = "Item 2";
$array[1][2] = "Item 3";

creates an array of 2 items, each containing 3 items.

Upvotes: 0

Related Questions