【发布时间】:2016-04-11 13:59:46
【问题描述】:
我意识到有很多关于多维数组和 foreach 循环的问题,我花了几个小时阅读它们并试图让我自己的循环工作——但没有成功。如果解决方案重复,我将删除我的问题(如果愿意,可以链接到另一个问题)。
现在,挑战:
- 使用返回的 MYSQL 结果数组。结果来自关联数组中的多个连接表。现在我需要将其转换为我需要的多维数组。
- 我已经完成了大部分工作,但我的问题是循环遍历并将新项目添加到数组中的正确位置。
这里有一些代码:
//example of how array is setup in the way I want, this part works.
foreach($results as $i => $a):
//some other code is here, see below.
$items[$i] = [
"id" => $a['id'],
"itemid" => $a['itemid'],
"name" => $a['name'],
"def" => $a['def'],
"class" => $a['class'],
"timeline" => $a['timeline'],
"files" => [
[0] => [
"id" => $a['fileid'],
"name" => $a['filename'],
"path" => $a['filepath'],
"type" => $a['filetype']
]
],
"tags" => [
[0] => [
"id" => $a['tagid'],
"name" => $a['tagname']
]
]
];
endforeach;
然后我尝试了多种循环方式,以便仅在项目“id”与上一个相同时添加到“标签”或“文件”。这是我编辑器中的当前代码,无法正常工作:
//inside foreach loop, before above code
if($items[$i-1]['id'] == $a['id']):
//it is the same item, works to here.
if(in_array($a['filename'], $items[$i-1], FALSE)):
//add to files array for last item
$items[$i-1]['files'][] = [
"id" => $a['fileid'],
"name" => $a['filename'],
"path" => $a['filepath'],
"type" => $a['filetype']
];
elseif(in_array($a['tagname'], $items[$i-1], FALSE)):
//add to tags array for last item
$items[$i-1]['tags'][] = [
"id" => $a['tagid'],
"name" => $a['tagname']
];
endif;
else:// else it does the code above
如您所见,我最近的尝试是使用 in_array,我现在意识到它不适用于多维数组。我的问题是我不知道如何确定它是同一项目的新文件还是新标签。
最终,我想要一个包含多个“文件”和“标签”的“项目”数组。之后我要去json_encode和JS一起使用。
任何关于如何使它工作或优化它的建议,将不胜感激。
附:正如我上面提到的,我知道以前有人问过这个问题——尽管我无法让他们的解决方案为我工作。如果解决方案是重复的,我将删除这个问题(例如,它对其他人并没有真正的帮助)。感谢您的帮助,非常感谢!
【问题讨论】:
-
你的 PHP 版本是多少?在 PHP >= 5.5 上,您可以使用
array_column:in_array( $a['filename'], array_column( $items[$i-1]['files'], 'name' ) ) -
感谢@fusion3k 的提示。我会阅读有关该功能的文档并试一试。
标签: php mysql arrays multidimensional-array