我是PHP初学者并且有一个问题:
我有一个多维关联数组:
array(
"X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
"Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
"Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
)
并且需要将"" => ""
添加到每个元素X,Y,Z,所以它将是:
array(
"X" => array( "" => "", "x1" => "1", "x2" => "2", "x3" => "3" ),
"Y" => array( "" => "", "y1" => "1", "y2" => "2", "y3" => "3" ),
"Z" => array( "" => "", "z1" => "1", "z2" => "2", "z3" => "3" )
)
X,Y,Z名称经常被更改,所以我需要先获取一个密钥名称然后添加新值。
我想以某种方式使用foreach。我尝试过,但可以实现它。
由于
答案 0 :(得分:1)
检查以下代码:
<?php
$temp = array(
"X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
"Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
"Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
);
$you_array = array();
foreach($temp as $k=>$v){
array_unshift($v, " ");
$you_array[$k] = $v;
}
print_r($you_array);
?>
Out put:
Array (
[X] => Array ( [0] => [x1] => 1 [x2] => 2 [x3] => 3 )
[Y] => Array ( [0] => [y1] => 1 [y2] => 2 [y3] => 3 )
[Z] => Array ( [0] => [z1] => 1 [z2] => 2 [z3] => 3 )
)
答案 1 :(得分:1)
<?php
$temp = array(
"X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
"Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
"Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
);
$you_array = array();
foreach($temp as $k=>$v){
$v = array_merge([""=>""],$v);
$you_array[$k] = $v;
}
print_r($you_array);
?>
答案 2 :(得分:0)
您可以使用array_unshift向阵列添加新元素。
如前所述,创建一个foreach循环并将新元素添加到每个子数组中:
$new = array("new_key" => "");
foreach ($yourArray as $key => $value)
array_unshift($yourArray[$key], $new);
小心:您的新元素需要一个键值。空键(就像你提到的那样)是不可能的。如果您只是添加一个没有键array("")
的新元素,则会添加一个数字键(0 => "")
。将修改现有数字键以从零开始计数。
答案 3 :(得分:0)
我认为这就是你要找的东西
[akshay@localhost tmp]$ cat test.php
<?php
$array=array(
"X" => array( "x1" => "1", "x2" => "2", "x3" => "3" ),
"Y" => array( "y1" => "1", "y2" => "2", "y3" => "3" ),
"Z" => array( "z1" => "1", "z2" => "2", "z3" => "3" )
);
// Input
print_r($array);
// & reference
foreach($array as &$sub_array)
{
$sub_array = array(""=>"")+$sub_array;
}
// Output
print_r($array);
?>
输出
[akshay@localhost tmp]$ php test.php
Array
(
[X] => Array
(
[x1] => 1
[x2] => 2
[x3] => 3
)
[Y] => Array
(
[y1] => 1
[y2] => 2
[y3] => 3
)
[Z] => Array
(
[z1] => 1
[z2] => 2
[z3] => 3
)
)
Array
(
[X] => Array
(
[] =>
[x1] => 1
[x2] => 2
[x3] => 3
)
[Y] => Array
(
[] =>
[y1] => 1
[y2] => 2
[y3] => 3
)
[Z] => Array
(
[] =>
[z1] => 1
[z2] => 2
[z3] => 3
)
)