从另一个数组中提取数组值

时间:2012-01-12 09:46:51

标签: php arrays

嗨我在php中想要将数组值提取到新数组中,使用以下逻辑

旧数组

index|value
0=23
1=34
2=45
3=56
4=56
5=78
6=45
7=67
8=56
9=45

我希望新的数组存储来自旧系列的索引值:0,1,4,5,8,9 ......等等。

3 个答案:

答案 0 :(得分:1)

看起来你想要一个“拿两个,一滴两个”的序列,这样就可以了;

$input = array(23, 34, 45, 56, 56, 78, 45, 67, 56, 45);
$output = array();

$count = count($input);
for($i = 0; $i < $count; $i++)
{
  $output[$i] = $input[$i];
  if($i % 4 == 1)
    $i += 2;
}

var_dump($output);

答案 1 :(得分:0)

我不完全确定你要做什么,但我会尽我所能回答。

要使用原始数组中的值获取新数组,可以使用array_values() DOCs

对于只使用array_keys() DOCs的键的数组。

要按数值对数组进行排序,请使用asort() DOCs

然后获取排序的数组值,但使用顺序键:

$array = array(53,23,43);
sort($array);

请参阅sort() manual page

答案 2 :(得分:0)

正如练习一样,利用SPL

的解决方案
class stripes extends ArrayIterator {
    private $partial, $step;

    public function __construct($array, $step) {
        parent::__construct($array);
        $this->step = $step;
        $this->partial=0;
    }

    public function next() {
        $this->partial++;
        if ($this->partial >=$this->step) {
            for($step=$this->step;$step;$step--)
                parent::next();
            $this->partial=0;
        }
        parent::next();
    }
}

它有一个非常简单的用法:

$input = array(23,24,45,56,56,78,45,67,56,45);
$iterator = new stripes($input,2);
$result = iterator_to_array($iterator)

$result中,您拥有所需的阵列。你可以改变 条纹的大小只是改变了第二个参数 条带构造函数,而不会污染您的实时代码 空间

参考文献:

ArrayIterator
iterator_to_array

相关问题