我一直在环顾四周,但是找不到解决我问题的方法。将我的数组与变量关联时,似乎将它们转换为字符串。
我的问题是:如何在foreach循环中创建“小”数组而不将结果数组转换为字符串。然后,如何将那些新创建的数组注入另一个“大”数组中,以期望得到如下结果:
预期$ big变量输出
[["apple", 8, "leeloo"], ["chery", 0, "leeloo"],]
当前$ big变量输出
[apple, 8, 'leeloo'],[banana, 0, 'leeloo'],
当前PHP代码
<?php
$inputs = array(
"apple" => 8,
"banana" => 0
);
// transform inputs keys/values into arrays ("$small")
// inject those arrays into a new array ("$big")
$small = '';
$big = '';
foreach($inputs as $key => $value){
$small .= "[$key, $value, 'leeloo'],";
}
$big = array($small);
echo "small type: ", gettype($small); // string
echo "small output: ", $small; // [apple, 8, 'leeloo'],[banana, 0, 'leeloo'],
echo "big type: ", gettype($big); // array
echo "big output: ", implode($big); // [apple, 8, 'leeloo'],[banana, 0, 'leeloo'],
// expected output: [["apple", 8, "leeloo"], ["chery", 0, "leeloo"],]
?>
最终,我的目标是让我的$ big变量表现如下:
$big = [
["apple", 8, "leeloo"],
["banana", 0, "leeloo"],
];
您可以将$big
变量设置为空数组。
在循环中,使用您的值创建一个新数组,并将该数组添加到$big
$inputs = array(
"apple" => 8,
"banana" => 0
);
$big = [];
foreach($inputs as $key => $value){
$big[] = [$key, $value, 'leeloo'];
}
print_r($big);
输出
Array
(
[0] => Array
(
[0] => apple
[1] => 8
[2] => leeloo
)
[1] => Array
(
[0] => banana
[1] => 0
[2] => leeloo
)
)