我使用php glob 函数来获取子目录中的图像,我不知道每个目录中有多少文件
目录名是id
,我想对一个数组中目录中的所有图像进行分类
$arr = [];
$dir = dirname(__FILE__)."/gulets";
$files = glob($dir."/*/*_gulet_o_*");
foreach ($files as $file) {
$fullname = str_replace($dir."/", "", $file);
$name = explode("/", $fullname);
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
}
header('Content-Type: application/json');
echo json_encode($arr);
[
{
"id": "10",
"name": "asdsad_gulet_o_1.jpg"
},
{
"id": "10",
"name": "wqes_gulet_o_10.jpg"
},
{
"id": "10",
"name": "qwsdf_gulet_o_11.jpg"
},
{
"id": "10",
"name": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name": "fsdsc_gulet_o_13.jpg"
},
{
"id": "11",
"name": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name": "dsyjhk_gulet_o_15.jpg"
},
.
.
我需要改变它:
[
{
"id": "10",
"name1": "asdsad_gulet_o_1.jpg",
"name2": "wqes_gulet_o_10.jpg",
"name3": "qwsdf_gulet_o_11.jpg"
"name4": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name1": "fsdsc_gulet_o_13.jpg"
"name2": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name1": "dsyjhk_gulet_o_15.jpg"
.
.
答案 0 :(得分:2)
你想要这样的东西:
foreach ($arr as $a) {
$new_arr[$a['id']]['names'][] = $a['name'];
}
答案 1 :(得分:1)
我认为创建name1
,name2
,name3
等索引并不实用。您应该创建索引为names
的子阵列,然后输入您的名字。尝试这样的代码:
<?php
$array = array(
array('id'=>1, 'name'=>'qwerty'),
array('id'=>2, 'name'=>'asdf'),
array('id'=>2, 'name'=>'hjkl'),
array('id'=>1, 'name'=>'cvbnm'),
array('id'=>1, 'name'=>'yuiop'),
);
$groups = array();
foreach($array as $singleRow)
{
if(!isset($groups[$singleRow['id']]))
$groups[$singleRow['id']] = array('id'=>$singleRow['id'], 'names'=>array());
$groups[$singleRow['id']]['names'][] = $singleRow['name'];
}
$json = json_encode(array_values($groups));
var_dump($json);
输出:
[{"id":1,"names":["qwerty","cvbnm","yuiop"]},{"id":2,"names":["asdf","hjkl"]}]
答案 2 :(得分:0)
而不是 -
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
你可以使用像 -
这样的东西$nameKey = 'name' . $name[0];
$name1 = array('id'=>$name[0],$nameKey =>$name[1]);
if (!empty($arr[$name[0]])) {
$arr[$name[0]] = $arr[$name[0]] + $name1;
}
else {
$arr[$name[0]] = $name1;
}
并在foreach()循环结束后执行 -
$arr = array_values($arr);