php - 如何在不使用 foreach 结构的情况下组合数组值和单独的常量?

标签 php arrays loops foreach

我正在尝试寻找一种更简单的方法来从现有数组和值创建新数组。我想优化两个结构相似的例程。第一个的形式是:

$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/

相关文章:

c++ - 数组数据类型声明 C++

PHP : Array key containing special character not found

python - numpy 数组的顺序如何影响乘法速度?

php - 将键值对数组转换为关联数组

php - 如何过滤Excel中的重复数字并将数据发送到MySQL,并且我想在Php中显示警报消息?

php - 如何从 key : value meta table in mysql? 加入数据

php - 单击后退按钮时如何修复确认表单重新提交?

php - mysql 更新表缩写

Perl,在循环外使用来自 While 循环内的变量?

python - 如何在Python中解密我知道其模式的字符串?