【问题标题】:foreach until find some valueforeach 直到找到一些值
【发布时间】:2018-02-02 02:45:55
【问题描述】:

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

这是我的 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 或空值

【问题讨论】:

  • 你有$filter_id = 10,但你从不使用它。
  • @ryantxr 它可以为空,因为我想获取所有类别及其信息,并且我想获取特定类别信息和父项

标签: php arrays foreach


【解决方案1】:

不是最优解,但可以使用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

【讨论】:

  • 非常感谢您的回答。但我知道这个解决方案:(如果你知道,你能向我解释一下 wordpress 是如何做到这一点的。再次感谢你的时间
  • @oxmixpro,不幸的是,我从未使用过 WordPress,所以我不知道他们自己是如何做到的。
  • @oxmixpro 您可能应该为您的问题提供所需的所有上下文。这样可以防止人们浪费时间来帮助您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2019-11-08
  • 2022-01-12
相关资源
最近更新 更多