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条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化