2017-02-22 174 views
0

我希望这是问这个问题的最好方法。不知道该怎么说。我认为有一个本地PHP函数来确定这一点,这导致我认为,也许我的搜索措辞不是最好的。如何区分[key]和[value]与其他[key]和[value]的父数组[key]?

我想在我的数组中搜索特定的[key] => [value]。

如果在我的数组中找到[key] => [value],我想从它的数组父元素中获得另一个[key] => [value]。

从我的代码的例子来解释。

实施例1:

如果[post_type] = [页]我想要得到[activate_layout] = [值]从数组[0]。

实施例2:

如果[post_type] = [交]我想要得到[activate_layout] = [值]从阵列[1]。

一般概念实施例3:

如果[post_type] = [X]我想要得到[activate_layout] = [X]从其父阵列[X]。

我的问题是我怎样才能通过它的父数组[key]区分[key]和[value]与另一个[key]和[value]?

下面是我的数组数据如何存储。

[post_type_layouts] => Array 
     (
      [0] => Array 
       (
        [context] => Array 
         (
          [option] => Array 
           (
            [activate_layout] => 1 
            [post_type] => page 
           ) 

         ) 

       ) 

      [1] => Array 
       (
        [context] => Array 
         (
          [option] => Array 
           (
            [activate_layout] => 1 
            [post_type] => post 
           ) 

         ) 

       ) 

     ) 
+0

需要递归函数http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php –

+0

你能展示如何看看最终结果吗?它会增加你获得快速帮助的机会。 – RomanPerekhrest

+0

嗨。下面是一个没有递归函数的答案。我只是为了我的需要对它进行了一些修改,我对批准的答案进行了评论。谢谢! –

回答

1

如果我真的明白你的问题,我认为你的解决方案更简单。

我按照这个阵列状例如:

$arrayTest = [ 
0 => [ 
    'context' => [ 
     'option' => [ 
      'post_type' => 'page', 
     ], 
    ], 
], 

1 => [ 
    'context' => [ 
     'option' => [ 
      'post_type' => 'post', 
     ], 
    ], 
], 
]; 

,并在此冲浪和得到的post_type父值我只创建一个foreach steatment,我用switch steatment检查post_type值。这件事情是这样的:

foreach ($arrayTest as $subLevel1) { 
switch ($subLevel1['context']['option']['post_type']) { 
    case 'page': 
     $subLevel1['context']['option']['active_layout'] = 0; 
     break; 

    default: 
     $subLevel1['context']['option']['active_layout'] = 1; 
     break; 
} 
print_r($subLevel1); 
} 

我的回报是像上面你的样品,我认为这个解决您的问题:

php -f testArray.php 
    Array 
     (
     [context] => Array 
      (
      [option] => Array 
       (
       [post_type] => page 
       [active_layout] => 0 
      ) 
     ) 
    ) 
    Array 
    (
     [context] => Array 
     (
      [option] => Array 
      (
       [post_type] => post 
       [active_layout] => 1 
      ) 
      ) 
     ) 

好代码!

+0

这看起来很棒!我认为这很容易以更轻的方式回答我的问题。我会玩弄它来确认和回答/更新。 –

+0

谢谢!这让我以适当的方式开始!我需要删除开关的情况下,因为我需要的情况下值是一个Wordpress函数来匹配var,像这样...$ post_type = $ post_type_layout ['context'] ['option'] ['post_type']; if(is_singular($ post_type)){// This custom code ...} elseif(!is_singular($ this_post_type)){// This default code ...} –

+0

不客气!任何时候,我们需要的一切都会让我们走向正确的道路。好的代码! – vicentimartins