PHP: get keys of independent arrays

后端 未结 2 1267
醉酒成梦
醉酒成梦 2020-12-19 20:53

I have two arrays.

Example of the first array:

$arrayOne = array
(
    \'fruit\' => array(
        \'apples\' => array(),
        \'oranges\' => array(),
         


        
相关标签:
2条回答
  • 2020-12-19 21:21
    $arrayOne = //...
    
    $arrayTwo = //...
    
    function getPosition(array $arr, $key) {
        $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr),
            RecursiveIteratorIterator::SELF_FIRST);
        $pos = array();
        foreach ($it as $k => $v) {
            if (count($pos) - 1 > $it->getDepth()) {
                array_pop($pos);
                $pos[$it->getDepth()]++;
            }
            elseif (count($pos) - 1 < $it->getDepth()) {
                array_push($pos, 0);
            }
            else {
                $pos[$it->getDepth()]++;
            }
            if ($k === $key) {
                return $pos;
            }
        }
    }
    
    function getElementKey(array $arr, array $position) {
        $cur = $arr;
        $curkey = null;
        foreach ($position as $p) {
            reset($cur);
            for ($i = 0; $i < $p; $i++) {
                next($cur);
            }
            $curkey = key($cur);
            $cur = current($cur);
        }
        return $curkey;
    }
    
    var_dump(getPosition($arrayOne, "battlestar-galactica"));
    var_dump(getElementKey($arrayTwo, array(1, 3, 1)));
    

    gives:

    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(3)
      [2]=>
      int(1)
    }
    string(19) "tablestar-neglectia"
    

    You can feed the result of getPosition to getElementKey:

    getElementKey($arrayTwo, getPosition($arrayOne, "battlestar-galactica"));
    
    0 讨论(0)
  • 2020-12-19 21:26

    Check out array_keys from both arrays and then map the positions. Like array_keys for your arrays will give you -

    $arrayKeyOne = array('fruit', 'vegetables', 'meat', 'other');
    $arrayKeyTwo = array('frewt', 'vetchteblz', 'meat', 'mother');
    

    Then a $arrayKeyTwo[array_search($one, $arrayKeyOne)] shuld give you what you want. Let know if this helps.

    0 讨论(0)
提交回复
热议问题