我有一系列数组,其值从1到5.几乎每个数组都有缺失值,有些甚至没有任何值。我的目标是用0填充缺失值。所有这些数组都存储在一个多维数组中。
我的数组看起来像:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 5
)
[3] => Array
(
[0] => (this array has no values)
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
应该如何:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 0
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
[4] => 5
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
任何帮助都会得到满足!
答案 0 :(得分:1)
这样的事情(array_pad()
不会做到这一点)。 $myArray
是您的源数组。完成的数组在$result
中返回:
$result = array();
foreach( $myArray as $subKey=>$subArray ) {
for( $i=0; $i<5; $i++ ) {
if( isset( $subArray[$i] )) {
$result[$subKey][$i] = $subArray[$i];
} else {
$result[$subKey][$i] = 0;
}
}
}
注意,我们会复制数组。你不能就地填充阵列。
答案 1 :(得分:1)
对于每个子数组,循环遍历数字1到5,如果该值存在,则将其键设置为小于其值的值:
$newarray = array();
foreach($arr as $key => $subarr) {
for ($i = 1; $i <= 5; $i++) {
if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
else $newarray[$key][$i - 1] = 0;
}
}
$newarray
是您的输出,$arr
是您的输入数组。
答案 2 :(得分:1)
您可能需要注意PHP并不真正做多维数组。它只允许您将2个平面阵列关联在一起,这不是真正的多维度。
这不起作用,会产生上述结果。
$ menu [1] =“我的训练”; //不是$ menu [1] [0]
$menu[1][1] = "To Do List";
$menu[1][2] = "Catalog";
$menu[1][3] = "Self-Report";
$menu[1][4] = "Completions";
$ menu [2] =“经理”;
$menu[2][1] = "Direct Reports";
$menu[2][2] = "Incompletes";
$menu[2][3] = "Completions";
$ menu [3] =“教练”;
$menu[3][1] = "My Classes";
$menu[3][2] = "Printables";
$menu[3][3] = "Qualifications";
这确实有效。
$ menu [1] =“我的训练”; //不是$ menu [1] [0]
$submenu[1][1] = "To Do List";
$submenu[1][2] = "Catalog";
$submenu[1][3] = "Self-Report";
$submenu[1][4] = "Completions";
$ menu [2] =“经理”;
$submenu[2][1] = "Direct Reports";
$submenu[2][2] = "Incompletes";
$submenu[2][3] = "Completions";
$ menu [3] =“教练”;
$submenu[3][1] = "My Classes";
$submenu[3][2] = "Printables";
$submenu[3][3] = "Qualifications";
$子菜单仅通过第一个键编号与$ menu相关,因为$ submenu没有第一个维度值。
答案 3 :(得分:-1)
自从我编写任何PHP以来已经很多年了但这样的事情可能会让我觉得这个技巧?
for($i = 0; $i < 5; $i++)
{
if(empty($myArray[$i])
{
$myArray[$i] = 0;
}
}