douye1940 2011-02-11 03:26
浏览 50
已采纳

PHP - 基于索引位置增加数组

I have a script which handles the naming of parent/child elements on another page. The format for the name is like E5-2-3 which represents the third child of the second child of the fifth element.

What I need to do is pass in the parent name to the function and return the name for the next child. This value would be the increment of the last child or 1 if it is the first child.

(I hope this makes some sense to someone)

The index array looks something like this:

1=>null
2=>null
3=>
    1=>null
    2=>null
    3=>
        1=>null
4=>null
5=>
    1=>null
    2=>
        1=>null
        2=>null
        3=>null //the element I was talking about above
6=>
    1=>null
7=>null

My Code so far is

    $projectNumber = $_GET['project_number'];
    @$parentNumber = $_GET['parent_number']; //suppressed as it may not be set

    $query = mysql_query("SELECT e_numbers FROM project_management WHERE project_number = '$projectNumber'");
    $resultArray = mysql_fetch_assoc($query);
    $eNumbers = unserialize($resultArray['e_numbers']);

    if (!is_array($eNumbers)&&!isset($parentNumber)){ //first e_number assigned
        $eNumbers[1] = null; //cant possibly have children so null for now
        $nextENumber =  'E1';
    }else{
        if (!isset($parentNumber)){
            $nextNumber = count($eNumbers)+1;
            $eNumbers[$nextNumber] = null; //cant possibly have children so null for now
            $nextENumber = 'E'.$nextNumber;
        }else{
            $parentIndex = explode('-', str_replace('E', '', $parentNumber));
            //$nextENumber = //assign $nextENumber the incremented e number
        }
    }

    echo $nextENumber;

            //(then goes on to update sql etc etc)

This is all fine but for the line where I need to get/assign deep numbers. I think this should be some kind of recursive function based on the $parentIndex and $eNumbers arrays, however I'm a bit out of my depth when it comes to recursion.

Any pointer in the right direction will be a great help.

PS If there is a better way to handle incrementing parent/child relationships I'm all ears. The only thing out of my control is the format of the numbers being passed in/out (Has to be EX-Y-Z-...)

UPDATE I was able to develop @ircmaxell 's function to function more better in my context. The function required you to pass in a zero based array(can be empty) and an optional path. It returns the new path and updates the index array to include the new path. An error message is returned if the index is not found.

function getNextPath(&$array, $path) { //thanks to  ircmaxell @ stackoverflow for the basis of this function
            $newPath = '';
            $tmp =& $array;
            if (is_string($path)) {
                $path = explode('-', str_replace('E', '', $path));
                $max = count($path);            
                foreach ($path as $key => $subpath) {
                    if (is_array($tmp)) {
                        if (array_key_exists($subpath, $tmp)){
                            $tmp =& $tmp[$subpath];
                                $newPath[] = $subpath;
                        }else{
                            return "Parent Path Not Found";
                        }

                    }
                }
            }           
            $tmp[] = null;
            $newPath[] = count($tmp)-1;
            if (count($newPath)>1){
                $newPath = implode('-', $newPath);
            }else{
                $newPath = $newPath[0];
            }           
            return "E".$newPath;
        }
  • 写回答

1条回答 默认 最新

  • douzen1896 2011-02-11 03:35
    关注

    Here's one way:

    function incrementPath(&$array, $path) {
        if (is_string($path)) {
            $path = explode('-', str_replace('E', '', $path);
        }
        $tmp =& $array;
        foreach ($path as $subpath) {
            if (is_array($tmp) && isset($tmp[$subpath])) {
                $tmp =& $tmp[$subpath];
            } else {
                return false; // Could not find entire path
            }
        }
        $tmp++;
        return true;
    }
    

    Now, if you want it to dynamically create paths, just change the return false; to:

    $tmp[$subpath] = array();
    $tmp =& $tmp[$subpath];
    

    And then add a check after the loop to see if it's not an integer, and explicitly set to 0 if it isn't...

    Edit: AHHH, now I understand:

    function getNextPath(&$array, $path) {
        if (is_string($path)) {
            $path = explode('-', str_replace('E', '', $path);
        }
        $newPath = '';
        $tmp =& $array;
        $max = count($path) - 1;
        foreach ($path as $key => $subpath) {
            if (is_array($tmp) && isset($tmp[$subpath])) {
                $tmp =& $tmp[$subpath];
                if ($key < $max) {
                    $newPath .= '-'.$subpath;
                }
            } else {
                return 'E' . ltrim($newPath . '-1', '-'); // Could not find entire path
            }
        }
        if (is_array($tmp)) {
            return 'E' . ltrim($newPath . '-' . count($tmp), '-');
        } else {
            //it's a value, so make it an array
            $tmp = array();
            return 'E' . ltrim($newPath . '-' . 1, '-');
        }
    }
    

    I think that should do what you want (it returns the next available path under what you're looking for). }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能