方式一:使用range和zip实现

import std.algorithm, std.range, std.stdio;

auto array_combine(T)(T[] keys, T[] values) { if (keys.length != values.length) { throw new Exception("The number of elements in keys and values does not match."); } return zip(keys, values).array; }

void main() { auto keys = ["green", "red", "yellow"]; auto values = ["avocado", "apple", "banana"]; auto result = array_combine(keys, values); writeln(result); }

方式二:使用foreach实现

import std.algorithm, std.stdio;

auto array_combine(T)(T[] keys, T[] values) { if (keys.length != values.length) { throw new Exception("The number of elements in keys and values does not match."); } T[T] result; foreach (i, key; keys) { result[key] = values[i]; } return result; }

void main() { auto keys = ["green", "red", "yellow"]; auto values = ["avocado", "apple", "banana"]; auto result = array_combine(keys, values); writeln(result);

请用D语言实现php的array_combine函数array_combinearray $keys array $values arrayCreates an array by using the values from the keys array as keys and the values from the values array as the corresponding valuesP

原文地址: https://www.cveoy.top/t/topic/fvx9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录