文章詳情頁
一維數組分割成二維數組
瀏覽:110日期: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. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?2. mysql - 把一個表中的數據count更新到另一個表里?3. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?4. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題5. visual-studio - Python OpenCV: 奇怪的自動補全問題6. linux - Ubuntu下編譯Vim8(+python)無數次編譯失敗7. node.js - nodejs開發中常用的連接mysql的庫8. mysql 查詢身份證號字段值有效的數據9. 視頻文件不能播放,怎么辦?10. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處
排行榜
