在PHP中动态创建数组

时间:2014-01-23 17:15:53

标签: php

我被困住了。我需要根据提供的数字创建一个数组,我无法想到任何方法。

需要做的是: 如果数字为1,则数组必须为array("2","3","4","10")

如果数字为2,则数组必须为array("3","4","10")

如果数字为3,则数组必须为array("4","10")

如果数字为4,则数组必须为array("10")

如果数字为10,则不需要数组。

除了使用大量ifselseifs之外,还有更优雅的方法吗?这只是针对这个问题。实际情况更糟。

我的方法:

if ($num == 1) {
    $array = array("2","3","4","10");
} elseif ($num == 2) {
    $array = array("3","4","10");
} etc.

5 个答案:

答案 0 :(得分:5)

使用array_searcharray_slice

$array = array(1, 2, 3, 4, 10);

$result = array_slice($array, array_search($num, $array) + 1);

示例:

$array = array(1, 2, 3, 4, 10);

foreach ($array as $num)
{
  echo '<pre>' . print_r(array_slice($array, array_search($num, $array) + 1), TRUE) . '</pre>';
}

这给出了:

1:
Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 10
)

2:
Array
(
    [0] => 3
    [1] => 4
    [2] => 10
)

3:
Array
(
    [0] => 4
    [1] => 10
)

4:
Array
(
    [0] => 10
)

10:
Array
(
)

答案 1 :(得分:3)

最简单的解决方案:

$source = array(null,"2","3","4","10");
$array = array_slice($source, $number);

测试用例:

foreach ([1,2,3,4,10] as $n) {
    $array = array_slice($source, $n);
    print_r($array);
}

输出:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 10
)
Array
(
    [0] => 3
    [1] => 4
    [2] => 10
)
Array
(
    [0] => 4
    [1] => 10
)
Array
(
    [0] => 10
)
Array
(
)

Demo

答案 2 :(得分:0)

试试这个:

$arr = array(); // starting array
switch($n) { // your number here
  case 1:
    $arr[] = 2;
    // fallback

  case 2:
    $arr[] = 3;
    // fallback

  case 3:
    $arr[] = 4;
    // fallback

  case 4:
    $arr[] = 10;
    // fallback

  case 10: break; // done
}

现在你的数组在$arr中,基于它只包含所需值的入口点。

答案 3 :(得分:0)

$num = 10;
$source = array("2","3","4","10");
$i = $num;
$array = array();
while ($i <= 4):
    $array[] = $source[$i-1];
    $i++;
endwhile;

答案 4 :(得分:-1)

$origin = array("1","2","3","4","10");
$flag = false;
$array = array();
foreach($origin as $value){
    if($flag == true){
        $array[] = $value;
        continue;
    }
    if($value == $num){
        $flag = true;
    }
}