Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我不能在PHP中创建一个包含4个元素的数组,但我有4个包含1个元素的数组_Php_Arrays - Fatal编程技术网

我不能在PHP中创建一个包含4个元素的数组,但我有4个包含1个元素的数组

我不能在PHP中创建一个包含4个元素的数组,但我有4个包含1个元素的数组,php,arrays,Php,Arrays,我对PHP中的数组有一个问题 我需要执行下一个阵列: array( "Componente 1" => "1", "Componente 2" => "2", "Componente 3" => "3", "Componente 4" => "4", ) 我明白了: array( array( "Componente 1" => "1", ), array( "Componente 2" =&

我对PHP中的数组有一个问题

我需要执行下一个阵列:

array(
   "Componente 1" => "1",
   "Componente 2" => "2",
   "Componente 3" => "3",
   "Componente 4" => "4",
)
我明白了:

array(
    array(
      "Componente 1" => "1",
    ),
    array(
      "Componente 2" => "2",
    ),
    array(
      "Componente 3" => "3",
    ),
    array(
      "Componente 4" => "4",
    ),
)
我的代码是

$element = array();
foreach ($components as $component)
{
    array_push($element, array($component[0] => $component[1]]);
}
我还试过:

$element = array();
foreach ($components as $component)
{
    $element[] = array($component[0] => $component[1]]);
}
你能帮我吗


非常感谢

我相信这应该是可行的:

$element = array();
foreach ($components as $component)
{
    $element[$component[0]] = $component[1];
}

这是假设
$components
是一个类似
[[“Component 1”、“1”]、[“Component 2”、“2”]、…]的数组

我相信这应该可以:

$element = array();
foreach ($components as $component)
{
    $element[$component[0]] = $component[1];
}

这是假设
$components
是一个类似
[[“Component 1”、“1”]、[“Component 2”、“2”]、…]
的数组,只需一个foreach,其中一个
[/code>具有键和值,您忘记在第二个代码中使用键,而在“not present”中使用索引
1

 $new=array();
   foreach($arr as $key=>$value){
  $new[] = [$key=>$value];
 }
 print_r($new);

现场演示:

只需一个带有键和值的foreach
[]
,您忘记在第二个代码中使用键,在“不存在”中使用索引
1

 $new=array();
   foreach($arr as $key=>$value){
  $new[] = [$key=>$value];
 }
 print_r($new);

现场演示:

使用array\u merge代替array\u push,看看会发生什么

使用array\u merge代替array\u push,看看会发生什么

非常感谢!就这样!没问题!你能把这个标记为正确答案吗?非常感谢!就这样!没问题!你能把这个标记为正确答案吗?不清楚你在问什么。请举例说明你的预期产出。不清楚你在问什么。请提供一个预期输出的示例。