将数组的特定索引传递给新数组 - php

时间:2015-05-29 09:13:31

标签: php arrays

我想从数组中删除索引并将其插入新数组中。我想要两件事,我试图解释一件是

Array
    (
        [index1] => Deleted
        [index4] => Inserted
    )
     Array
(

        [index3] => test
        [index4] => Inserted
    )
     Array
    (

        [index2] => numbers
        [index3] => test
        [index4] => Inserted
    )
     Array
    (
        [index1] => Deleted

    )

现在我想如果arraysize是1

 foreach($array as $arrays){
    array_push($array1,($arrays[0]));
      unset ($arrays[0]);

 }

我想删除

Array
    (
        [index1] => Deleted

    )

$array$array

 [index1] => Deleted

第二个是$array是否

Array
(

    [index2_123] => numbers
    [index3_level] => test
    [index4_test] => Inserted
)

我想要一个$array1

的新数组
Array
(

    [index3_level] => test

)

$array1被修改为

Array
(

    [index2_123] => numbers
    [index4_test] => Inserted
)

4 个答案:

答案 0 :(得分:2)

试试这种方式,

$arr = Array
    (
        'index1' => 'Deleted',
        'index2' => 'numbers',
        'index3' => 'test',
        'index4' => 'Inserted'
    );
$arr1 = $arr2 = array();
$i = 0;
foreach($arr as $key => $value){
    if($i%2 == 0){
        $arr1[$key] = $value;
    }else{
        $arr2[$key] = $value;
    }
    $i++;
}

输出

$arr1
Array
(
    [index1] => Deleted
    [index3] => test
)

$arr2
Array
(
    [index2] => numbers
    [index4] => Inserted
)

如果您不需要该值,则可以将其用作

$i = 0;
foreach($arr as $key => $value){
    if($i%2 == 0){
        $arr[$key] = $value;
    }else{
        unset($arr[$key]);
    }
    $i++;
}
print_r($arr);

输出:

Array
(
    [index1] => Deleted
    [index3] => test
)

答案 1 :(得分:1)

循环遍历它们并生成数组 -

$new = array();
foreach($yourarray as $key => $val) {
    $index = str_replace('index', '', $key); // get the key index
    if($index % 2 != 0) { // check for odd or even
        $new[$key] = $val; // set the new array
        unset($yourarray[$key]); // delete from the main array
    }
}

<强>更新

对于任何索引使用计数器

$i = 0;
$new = array();
foreach($yourarray as $key => $val) {
    if($i % 2 != 0) { // check for odd or even
        $new[$key] = $val; // set the new array
        unset($yourarray[$key]); // delete from the main array
    }
    $i++;
}

答案 2 :(得分:1)

您可以使用array_fliparray_diff_key的组合来过滤第一个数组,然后使用array_diff过滤第二个数组:

$specificIndex = array('index1', 'index3');
$array1 = array_diff_key($array, array_flip($specificIndex));
$array2 = array_diff($array, $array1);

Demo

如果您希望只在某个数组中输入您选择的某些元素,则可以执行以下操作:

$specificIndex = array('index1', 'index3');
$selectedItem = array_intersect_key($array, array_flip($specificIndex));

Demo

答案 3 :(得分:0)

<?php
$array = array(
        'index1' => 'Deleted',
        'index2' => 'numbers',
        'index3' => 'test',
        'index4' => 'Inserted',
);
$specificIndex = 'index3';
$array1=array();
foreach($array as $key => $value){
if($key==$specificIndex){
 $array1[$key] = $value;
unset($array[$specificIndex]);
}
}
print_r($array);
print_r($array1);

http://3v4l.org/TvZ19