dongra1984 2015-05-29 09:13
浏览 46

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

I want to delete an index from array and insert it into in new array. I want two things which i tried to explain one is

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

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

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

    )

now i want if arraysize is 1

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

 }

i want to remove

Array
    (
        [index1] => Deleted

    )

from $array and $array to be

 [index1] => Deleted

second is if $array is

Array
(

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

i want a new array with $array1 as

Array
(

    [index3_level] => test

)

and $array1 is modified to

Array
(

    [index2_123] => numbers
    [index4_test] => Inserted
)
  • 写回答

4条回答 默认 最新

  • douzao9845 2015-05-29 09:16
    关注

    Loop through them and generate the array -

    $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
        }
    }
    

    Update

    For any index use a counter

    $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++;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致