1

我有一系列值从 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...

)

任何帮助将不胜感激!

4

4 回答 4

2

对于每个子数组,循环遍历数字 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你的输入数组在哪里。

于 2012-11-22T22:03:49.040 回答
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;
    }
  }
}

请注意,我们会复制数组。您不能就地填充数组。

于 2012-11-22T22:02:43.623 回答
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";

$submenu 仅通过第一个键号与 $menu 相关,因为 $submenu 没有第一维值。

于 2012-11-23T19:53:40.533 回答
-1

自从我编写任何 PHP 以来已经有很多年了,但是我猜这样的东西可能会起作用吗?

for($i = 0; $i < 5; $i++)
{
  if(empty($myArray[$i])
  {
    $myArray[$i] = 0;
  }
}
于 2012-11-22T22:01:46.583 回答