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);
}
精彩评论