AI编程助手
AI免费问答

php判断数组有关问题

  2016-06-13 12:06   1077浏览 原创

php判断数组问题

本帖最后由 hxlb520 于 2014-09-19 08:53:23 编辑 我想在foreach()循环中只显示没有下级的大栏目(例如只显示代码中的大栏目一,大栏目四),有下级栏目的不显示 ,如何判断呢?

cid=栏目ID,name=栏目名称,parent_cid=子栏目的上级栏目ID

{"seller_cat":[
{"cid":"1","name":"大栏目一","parent_cid":"0"},
{"cid":"2","name":"大栏目二","parent_cid":"0"},
{"cid":"3","name":"子栏目二","parent_cid":"2"},
{"cid":"4","name":"子栏目三","parent_cid":"2"},
{"cid":"5","name":"大栏目三","parent_cid":"0"},
{"cid":"6","name":"子栏目一","parent_cid":"5"},
{"cid":"7","name":"大栏目四","parent_cid":"0"}
]}}
------解决思路----------------------
类方法,可以参考下。
$a = json_decode($s);<br>$ar = array();<br>foreach($a->seller_cat as $t) {<br>  if($t->parent_cid == 0 && ! array_filter($a->seller_cat, array(new T($t->cid), 'filter')))<br>    $ar[] = $t->name;<br>}<br>print_r($ar);<br>class T {<br>        private $cid;<br><br>        function __construct($cid) {<br>                $this->cid = $cid;<br>        }<br><br>        function filter($v) {<br>                return $v->parent_cid == $this->cid;<br>        }<br>}

------解决思路----------------------
foreach($a->seller_cats->seller_cat as $t) {
  if($t->parent_cid == 0 && ! array_filter($a->seller_cats->seller_cat, array(new T($t->cid), 'filter')))
    $ar[] = $t->name;
}

php免费学习视频:立即学习
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。