dongmufen8105 2017-01-03 00:47
浏览 108
已采纳

如何在PHP中找到特定索引后将数组拆分为两个?

I have an array that start with a specific index, always will be 43 the first index, after that I have info and I would like to split it into 2 after find the value products but not always the value products will be the index 64 it will be different everytime.

So I tried this to find the index where the value products is

$index = array_search('products', $data);

This way I can find the index where I would like to split the array in 2, but I have no idea how, I tried with array_chunk but I couldn't make it work

This is my original array:

Array
(
    [43] => 1234
    [44] => 001
    [45] => 100
    [46] => 0
    [47] => 0
    [48] => 2
    [49] => 
    [50] => 1234
    [51] => 001
    [52] => 100
    [53] => 0
    [54] => 0
    [55] => 2
    [56] => 
    [57] => 
    [58] => 
    [59] => 
    [60] => 
    [61] => 0
    [62] => 1
    [63] => 
    [64] => products
    [65] => 1234
    [66] => 001
    [67] => 100
    [68] => 0
    [69] => 0
    [70] => 2
    [71] => 
    [72] => 1234
    [73] => 001
    [74] => 100
    [75] => 0
    [76] => 0
    [77] => 2
    [78] => 
    [79] => 
    [80] => 
    [81] => 
    [82] => 
    [83] => 0
    [84] => 1
)

And I would like something like this:

Array
(
    [43] => 1234
    [44] => 001
    [45] => 100
    [46] => 0
    [47] => 0
    [48] => 2
    [49] => 
    [50] => 1234
    [51] => 001
    [52] => 100
    [53] => 0
    [54] => 0
    [55] => 2
    [56] => 
    [57] => 
    [58] => 
    [59] => 
    [60] => 
    [61] => 0
    [62] => 1
    [63] =>
)

Array
( 
    [65] => 1234
    [66] => 001
    [67] => 100
    [68] => 0
    [69] => 0
    [70] => 2
    [71] => 
    [72] => 1234
    [73] => 001
    [74] => 100
    [75] => 0
    [76] => 0
    [77] => 2
    [78] => 
    [79] => 
    [80] => 
    [81] => 
    [82] => 
    [83] => 0
    [84] => 1
)

Also without the index of the value products, do you have some idea what function can I use to achieve this or another way to do it? I hope you can help me, thank you.

  • 写回答

3条回答 默认 最新

  • douzheren3349 2017-01-03 01:05
    关注

    Almost, array_chunk() makes multiple pieces instead you want to slice the array in two pieces by a given key, this can be done with array_slice()

    $split = array_search('products', $data);
    
    print_r(array_slice($data, 0, $split))   // first part
    print_r(array_slice($data, $split + 1)); // second part
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料