我正在尝试寻找一种更简单的方法来从现有数组和值创建新数组。我想优化两个结构相似的例程。第一个的形式是:
$i = 0;
$new_array = array();
foreach ($my_array as $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$i++;
}
第二个形式的每个常量不是一个而是两个不同的值;注意 $value 在索引中出现在 $key 之前:
$i = 0;
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$new_array[$i][2] = $key; // different for each index of $my_array
$i++;
}
有没有一种方法可以使用 PHP 的数组运算符以更短、更高效的例程来优化这些过程? (当然有很多,我找不到一个似乎符合要求的。)
最佳答案
我相信结合 Wouter Thielen 关于其他解决方案的建议实际上对我来说是最好的答案。
对于我提供的第一个案例:
$new_array = array();
// $my_array is numeric, so $key will be index count:
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value);
};
我提供的第二种情况:
// $my_array is associative, so $key will initially be a text index (or similar):
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value, $key);
};
// This converts the indexes to consecutive integers starting with 0:
$new_array = array_values($new_array);
关于php - 如何在不使用 foreach 结构的情况下组合数组值和单独的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32283209/