【发布时间】:2020-05-19 15:57:58
【问题描述】:
我正在尝试使用<ul><li> 结构打印嵌套列表,但首先,我需要正确排序我的数据。我正在尝试使用多维数组来做到这一点,但我认为我需要一些递归代码。
实际上我正在这样做:
function array_key_exists_recursive(array $arr, $key) {
if (array_key_exists($key, $arr)) {
return true;
}
foreach ($arr as $element) {
if (is_array($element)) {
if (array_key_exists_recursive($element, $key)) {
return true;
}
}
}
return false;
}
$tags = array();
foreach($gallery as $gg){
$ftg = $gg['ftag']; //father category
$tg = $gg['tag']; //category
if(array_key_exists($ftg , $tags)) {
if(!in_array($tg, $tags[$ftg])) {
$tags[$ftg][$tg] = null;
}
}
else {
if(array_key_exists_recursive($tags, $ftg)) {
foreach($tags as $t=>$v) {
if(array_key_exists($ftg, $v)) {
$tags[$t][$ftg]= $tg;
};
}
}
else $tags[$ftg][$tg] = null;
}
}
显然,它只适用于二级数据结构,与我需要的不同。有人知道如何使这段代码工作吗?
更新:抱歉没有添加数据数组,我在这里发布一个小例子:
$gallery = array (
'0' => array (
'post-id' => 2,
'id' => 711,
'url' => 'http://localhost/wp-content/uploads/2019/12/WhatsApp-Video-2019-10-11-at-09.42.44.mp4',
'type' => 'video',
'album' => 'UNO',
'ftag' => 'Prova',
'tag' => 'Categoria di Prova',
'date' => '12/14/19'
),
'1' => array (
'post-id' => 2,
'id' => 341,
'url' => 'http://localhost/wp-content/uploads/2019/07/VID-20180925-WA0025.mp4',
'type' => 'video',
'album' => 'DUE',
'ftag' => 'Prova',
'tag' => 'Categoria dei Video',
'date' => '07/13/19'
),
'2' => array (
'post-id' => 2,
'id' => 614,
'url' => 'http://localhost/wp-content/uploads/2019/12/2-10-scaled.jpg',
'type' => 'image',
'album' => 'TRE',
'ftag' => 'Foto',
'tag' => 'Categoria delle foto',
'date' => '12/09/19',
'thumb' => 'http://localhost/wp-content/uploads/2019/12/thumb_400_2-10-scaled.jpg'
),
'3' => array (
'post-id' => 2,
'id' => 736,
'url' => 'http://localhost/wp-content/uploads/2020/01/iconfinder_camera-shutter_353402.png',
'type' => 'image',
'album' => 'QUATTRO',
'ftag' => 'Categoria delle foto',
'tag' => 'Categoria delle icone',
'date' => '01/29/20',
'thumb' => 'http://localhost/wp-content/uploads/2020/01/thumb_400_iconfinder_camera-shutter_353402.png'
),
'4' => array
(
'post-id' => 2,
'id' => 744,
'url' => 'http://localhost/wp-content/uploads/2020/02/DSC_0102-scaled.jpg',
'type' => 'image',
'album' => 'Titolo dell album',
'ftag' => 'Categoria delle icone',
'tag' => 'Terzo livello',
'date' => '02/03/20',
'thumb' => 'http://localhost/wp-content/uploads/2020/02/thumb_400_DSC_0102-scaled.jpg'
)
);
现在,我必须从这里创建一个仅包含类别(ftag 和标签)的数组,其中 ftag 是父类别,而 tag 是类别。我认为我可以使用某种嵌套数组在“级别”中排序, 稍后使用如下结构打印数据:
<ul>
<li>Category</li>
<li>Category
<ul>
<li>Subcategory</li>
<li>Subcategory
<ul>
<li>3rd Level</li>
</ul>
</li>
</ul>
</li>
<li>Category</li>
</ul>
【问题讨论】:
-
您可能想用数组本身的一些数据和结构以及所需的输出来更新您的问题。
-
如果没有数据数组,您将如何解决这个问题?
-
@FelippeDuarte 对不起,我从其他函数中检索了我的 $gallery 数组,它有点太大,无法发布,所以我添加了一个小例子
标签: php arrays recursion multidimensional-array