开发者

Working with array and unique key in php

开发者 https://www.devze.com 2023-01-28 10:00 出处:网络
How would I generate an array in which I need to use 开发者_如何学Pythona unique key and assign multiple values not unique to that key in a foreach loop?$result = array();

How would I generate an array in which I need to use 开发者_如何学Pythona unique key and assign multiple values not unique to that key in a foreach loop?


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消