2014-09-28 131 views
-1

我在创建基于现有数组的新数组时遇到问题。我有以下数组,并且想要将元素'id'与'parent'元素进行匹配。如果值相同,那么我想创建另一个数组,其中的子元素将在父元素下。从现有的数组中创建一个新的数组php

Array 
(
    [0] => Array 
     (
      [id] => 66 
      [parent] => 26 

     ) 

    [1] => Array 
     (
      [id] => 47 
      [parent] => 26 

     ) 

    [2] => Array 
     (
      [id] => 48   
      [parent] => 66 

     ) 

我想这是

Array 
    (
     [0] => Array 
      (
       [id] => 66 
       [parent] => 26 

      ) 
      [0] => Array 
      ( 

         [id] => 48 
         [parent] => 66 


      ) 

     [1] => Array 
      (
       [id] => 47 
       [parent] => 26 

      ) 

我坚持以下code.I已经拿到了值,但我不知道如何搭配使用阵列中的另一个元素。

foreach($firstlevel_results as $k => $v) 
{ 
    echo $v['id']."==".$v['parent']."==".$v['grandparent']."<br>"; 
} 

请建议是否有任何可能的方法。

+0

这难以证明自己试图为自己做! **这不是一个免费的编码网站**请阅读[如何提出一个很好的问题](http://stackoverflow.com/help/how-to-ask) – RiggsFolly 2014-09-28 14:25:57

+0

我仍然在尝试,并感谢链接。 – Raj 2014-09-28 14:29:44

+0

我编辑了我的问题。谢谢。 – Raj 2014-09-28 14:49:04

回答

0

尽管看起来很长的代码很容易。基本上,这个想法应该是它:

$my_array = Array(
    Array ('id' => 66, 'parent' => 26, 'grandparent' => 18), 
    Array ('id' => 23, 'parent' => 66, 'grandparent' => 57), 
    Array ('id' => 47, 'parent' => 26, 'grandparent' => 18), 
    Array ('id' => 48, 'parent' => 66, 'grandparent' => 26), 
    Array ('id' => 11, 'parent' => 66, 'grandparent' => 89), 
    Array ('id' => 200, 'parent' => 98, 'grandparent' => 26) 
); 

function merge($target_id, $target_array) { 
    #1) Find subarray with ID == $target_id 
    $new = array(); 
    # fast path (better than array_filter) 
    foreach ($target_array as $key => $sub_array) { 
     #find array with id == $target_id 
     if ($sub_array['id'] === $target_id) { 
      # first index will be super group 
      $new[0] = array($sub_array); 
      # removing it... 
      unset($target_array[$key]); 
      # it's not need continue anymore... 
      break; 
     } 
    } 

    # 2) and now gonna compare ids with targert_id 
    foreach ($target_array as $index => $sub_array) { 

     if ($sub_array['parent'] == $target_id) { 
      # index 0 is the super group as said early... 
      array_push($new[0], $sub_array); 

     } else { 
      # only push but not groups 
      array_push($new, $sub_array); 
     } 
    } 

    return $new; 
} 


print_r(merge(66, $my_array)); 

当然,有这码点可以改进的,但是这是想法。

+0

非常感谢@ felip.Almost close。只有一件事情,如果可以把id-23,48,11置于id 66之下。现在它们都处于同一水平。 – Raj 2014-09-28 15:43:10

+0

还有一个问题是我不能在函数内传递66,它需要在一个循环内计算。但这个想法很好,我会再试一次。谢谢。 – Raj 2014-09-28 15:56:22

+0

@Raj是的,但密钥将被覆盖。名为“merge”的函数通过第一个索引中的匹配连接匹配数组。我认为这是最好的方法。 – felipsmartins 2014-09-28 15:56:48

相关问题