0

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?

3 Answers 3

2
$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())

Sign up to request clarification or add additional context in comments.

1 Comment

This what i was doing only was assigning the multidimensional array elements wrongly. Thnaks
0

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.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.