策略在PHP自定义阵列功能 [英] Strategies for Custom Array Functionality in PHP
问题描述
我发现自己经常与寻求解决在PHP中的各种阵列布置的问题,回落的解决方案之外,我已经实施过挣扎。
I find myself often struggling with finding a solution to various array arrangement problems in PHP that fall outside of solutions that I have implemented before.
目前,我开始用此阵:
$tags = array(
array('tag_id' => 1, 'tag_name' => 'Hello', 'album_id => 1'),
array('tag_id' => 1, 'tag_name' => 'Hello', 'album_id => 2'),
array('tag_id' => 2, 'tag_name' => 'World', 'album_id => 1'),
array('tag_id' => 2, 'tag_name' => 'World', 'album_id => 2'),
array('tag_id' => 3, 'tag_name' => 'Again', 'album_id => 3')
);
和想组织它是这样:
$organized_tags = array(
array('tag_id' => 1, 'tag_name' => 'Hello', 'album_ids' => array(1,2)),
array('tag_id' => 2, 'tag_name' => 'World', 'album_ids' => array(1,2)),
array('tag_id' => 3, 'tag_name' => 'Again', 'album_ids' => array(3))
);
A)这将是解决此类问题的最佳策略是什么?
二)如何看待解决了上来在未来的通用阵列的问题?
a) what would be the best strategy for solving this kind of problem? b) how to think about solving generic array problems that come up in the future?
推荐答案
我可能需要从树叶中重新presenting模型数据本书的CakePHP作为数组。
I might take a leaf from the book of CakePHP in representing model data as arrays.
有了这个,你将有一个标签模式,以及相册样板。从数据给予,标签模型看起来像
With this, you would have a Tag model, and an Album model. From the data give, the Tag model looks like
['Tag' => ['tag_id' => 1, 'tag_name' => 'Hello']]
和,就目前而言,该专辑只具有ID
And, for the moment, the Album only has the id
['Album' => ['album_id' => 1']]
要重新present有组织的结构:
To represent the organized structure:
[
0 => [
'Tag' => ['tag_id' => 1, 'tag_name' => 'Hello'],
'Album' => [
0 => ['album_id' => 1],
1 => ['album_id' => 2]
],
1 => [
'Tag' => ['tag_id' => 2, 'tag_name' => 'World'],
'Album' => [
0 => ['album_id' => 1],
1 => ['album_id' => 2]
],
2 => [
'Tag' => ['tag_id' => 3, 'tag_name' => 'Again'],
'Album' => [
0 => ['album_id' => 3]
]
]
然而,这是不是你问什么。
However, this isn't what you've asked for.
要修改 $标记
到 $ organized_tags
,我会做一个标记
模型类,通过它采用 $标记
结构,迭代,并建立第二个结构。
To change $tags
to $organized_tags
, I'd do a Tag
model class that takes the $tags
structure, iterates through it, and builds the second structure.
public function toOrganizedTags($tags) {
$organizedTags = [];
foreach ($tags as $tag) {
if (!isset($organizedTags[$tag['tag_id']]) {
// make sure an entry exists. We assume that tag_name does not change between similar tag_id entries.
$organizedTags[$tag['tag_id']] = [
'tag_id' => $tag['tag_id'],
'tag_name' => $tag['tag_name'],
'album_ids' => []
];
}
$organizedTags[$tag['tag_id']]['album_ids'][] = $tag['album_id'];
}
// use array_values to strip the indexed keys
return array_values($organizedTags);
}
这篇关于策略在PHP自定义阵列功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!