文章详情页
一维数组分割成二维数组
浏览:130日期:2022-06-02 15:33:02
问题描述
[0.6,0.7,1,0,-1,-2,-3,0,0,-1,-5,-6,1,3,4]
分割成
[
[0.6,0.7,1],
[0],
[-1,-2,-3],
[0,0],
[-1,-5,-6],
[1,3,4]
]
这段程序应该怎么写
问题解答
回答1:方法蠢了点,但是能达到你想要的效果,希望可以帮到你,代码如下: public function index() {$array = [0.6, 0.7, 1, 0, -1, -2, -3, 0, 0, -1, -5, -6, 1, 3, 4];$result = [];foreach ($array as $value) { $count = count($result); if ($count> 0) {$single = $result[$count - 1];$index = end($single);if (0 === $index) { if (0 === $value) {$result = $this->handleArray($result, $single, $value, $count); } else {$result = $this->handleArrayTwo($result, $value); }} elseif ($index> 0) { if ($value handleArrayTwo($result, $value); } else {$result = $this->handleArray($result, $single, $value, $count); }} elseif ($index < 0) { if ($value>= 0) {$result = $this->handleArrayTwo($result, $value); } else {$result = $this->handleArray($result, $single, $value, $count); }} } else {$result = $this->handleArrayTwo($result, $value); }}var_dump($result);die; } private function handleArray($result, $single, $value, $index) {unset($result[$index - 1]);array_push($single, $value);array_push($result, $single);return array_values($result); } private function handleArrayTwo($result, $value) {$array = [];array_push($array, $value);array_push($result, $array);return $result; } // array(6) { // [0]=> // array(3) { // [0]=> // float(0.6) // [1]=> // float(0.7) // [2]=> // int(1) // } // [1]=> // array(1) { // [0]=> // int(0) // } // [2]=> // array(3) { // [0]=> // int(-1) // [1]=> // int(-2) // [2]=> // int(-3) // } // [3]=> // array(2) { // [0]=> // int(0) // [1]=> // int(0) // } // [4]=> // array(3) { // [0]=> // int(-1) // [1]=> // int(-5) // [2]=> // int(-6) // } // [5]=> // array(3) { // [0]=> // int(1) // [1]=> // int(3) // [2]=> // int(4) // } //}上一条:能不能出一集你的git的安装教程下一条:登录功能报错
相关文章:
1. mysql - 在不允许改动数据表的情况下,如何优化以varchar格式存储的时间的比较?2. css - chrome下a标签嵌套img 显示会多个小箭头?3. javascript - 网页打印页另存为pdf的代码一个问题4. vim - docker中新的ubuntu12.04镜像,运行vi提示,找不到命名.5. java中返回一个对象,和输出对像的值,意义在哪儿6. css3 - 纯css实现点击特效7. docker网络端口映射,没有方便点的操作方法么?8. mysql 为什么主键 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?9. javascript - Img.complete和img.onload判断图片加载完成有什么区别?10. javascript - 有适合开发手机端Html5网页小游戏的前端框架吗?
排行榜
