2013-07-23 21 views
0

我有以下數組,我唯一的值是子頁面的ID(在這種情況下是35)。我希望收到父母,所以當有更多的時候我可以循環所有的孩子(在這種情況下,我正在尋找數字34)。在PHP數組中找到父親

[34] => Array 
    (
     [id] => 34 
     [label] => Over Ons 
     [type] => page 
     [url] => 8 
     [children] => Array 
      (
       [0] => Array 
        (
         [id] => 35 
         [label] => Algemeen 
         [type] => page 
         [url] => 9 
        ) 

      ) 

    ) 

有沒有人有這個好的解決方案?

在此先感謝。

+0

你試過_anything_?看起來像你正在尋找一個非常基本的(遞歸)循環(函數) –

+4

如果你生成的數組,簡單地添加一個**引用**到父項:'$ parent = array(); $ child = array(); $ child [「parent」] =&$ parent; $ parent [] = $ child' - 然後你可以從每個孩子「向上」。並且不需要通過搜索整個數組來確定父項。對於最頂層,將父項設置爲'null' ofc。 – dognose

+1

檢查這一次http://stackoverflow.com/questions/17806116/how-to-search-by-value-and-get-key-in-multidimensional-arrays/17806172#17806172 – nickle

回答

0

嘗試:

foreach ($arr as $key => $value) { 
    foreach ($value["children"] as $child) { 
     if ($child["id"] == $you_look_for) return $key; // or $value["id"] ? 
    } 
} 

這 - 然而 - 只會返回一個包含一個孩子ID $you_look_for數組的第一個ID。

0

嘗試:

$input = array(/* your data */); 
$parentId = 0; 
$childId = 35; 

foreach ($input as $id => $parent) { 
    foreach ($parent['children'] as $child) { 
    if ($child['id'] == $childId) { 
     $parentId = $id; 
     break; 
    } 
    } 
    if ($parentId) { 
    break; 
    } 
} 

或用一個函數:

function searchParent($input, $childId) { 
    foreach ($input as $id => $parent) { 
    foreach ($parent['children'] as $child) { 
     if ($child['id'] == $childId) { 
     return $id; 
     } 
    } 
    } 
} 

$parentId = searchParent($input, $childId); 
0

當你創建數組(假設你是你自己創造它),參考添加到父:

<?php 

$parent = array("id" => 1, "parent" => null); 
$child = array("id" => 2, "parent" => &$parent); //store reference 
$child2 = array("id" => 3, "parent" => &$parent); //store reference 
$parent["childs"][] = $child; 
$parent["childs"][] = $child2; 

foreach ($parent["childs"] AS $child){ 
    echo $child["id"]." has parent ".$child["parent"]["id"]. "<br />"; 
} 

//2 has parent 1 
//3 has parent 1 
?> 

這允許您走陣列「非常光滑」,使用childsparent條目。 (基本上它的一棵樹,然後)

+0

我不建立這個數組。它是由我試圖修改的Magento擴展構建的。 –