foreach直到找到一些价值

时间:2018-02-01 16:07:01

标签: php arrays foreach

我有一个从数据库中获取类别的代码,但我不知道如何获取所有子类别(父母)。

这是我的PHP代码:

function get_the_category($allCats,$filter_id = null) {

$re_struct_cat = array();
$filter_id =  10;
$ids = array();
$xx = array();
foreach($allCats as $cat_key=>$cat_val) {
    $re_struct_cat[$cat_val["id"]] = array(
        "title" => $cat_val["cat_title"],
        "parent" => $cat_val["cat_parent"],
    );

$ids = array_merge($ids,array($cat_val["id"]));
}

foreach($ids as $k=>$v) {
    if($re_struct_cat[$v]["parent"]) {
        $xx[] = $re_struct_cat[$re_struct_cat[$v]["parent"]];
    }
}

return $xx;
//return $re_struct_cat;

//print_r($re_struct_cat);
}

我想要的是什么

我有3列[id,title,parent]

的表格
ID      TITLE       PARENT
1       Science     0
2       Math        1
3       Algebra     2
4       Analyse     2
5       Functions   4

因此,如果变量filter_id = 10我得到cat_parent = 4 所以我想获取该值并在数组中查找它,如果找到另一个cat_parent执行相同的操作,直到找到0或null值

1 个答案:

答案 0 :(得分:0)

这不是最佳解决方案,但您可以使用iterators

首先,创建可以处理类别的自定义迭代器:

class AdjacencyListIterator extends RecursiveArrayIterator
{
    private $adjacencyList;

    public function __construct(
        array $adjacencyList,
        array $array = null,
        $flags = 0
    ) {
        $this->adjacencyList = $adjacencyList;

        $array = !is_null($array)
            ? $array
            : array_filter($adjacencyList, function ($node) {
                return is_null($node['parent']);
            });

        parent::__construct($array, $flags);
    }

    private $children;

    public function hasChildren()
    {
        $children = array_filter($this->adjacencyList, function ($node) {
            return $node['parent'] === $this->current()['id'];
        });

        if (!empty($children)) {
            $this->children = $children;
            return true;
        }

        return false;
    }

    public function getChildren()
    {
        return new static($this->adjacencyList, $this->children);
    }
}

取自another answer

然后你可以简单地遍历这个迭代器,直到找到所需的id:

$id = 5;
$categories = [];
$result = null;
foreach ($iterator as $node) {
    $depth = $iterator->getDepth();
    $categories[$depth] = $node['categoryname'];

    if ($node['id'] === $id) {
        $result = array_slice($categories, 0, $depth + 1);
        break;
    }
}

这是the demo