我有一个如下所示的数组:
Array
(
[0] => stdClass Object
(
[blog_id] => 1
[site_id] => 1
[domain] => www.my-domain.dch
[path] => /another-blog-path/
[spam] => 0
[deleted] => 0
[blogname] => Another Company
[siteurl] => http://www.my-domain.dch/another-blog-path
)
...
[2340] => stdClass Object
(
[blog_id] => 28
[site_id] => 1
[domain] => www.my-domain.dch
[path] => /my-blog-path/
[spam] => 0
[deleted] => 0
[blogname] => Company Namy
[siteurl] => http://www.my-domain.dch/my-blog-path
)
)
我正在寻找的是创建一个新的数组,它将以下列形式聚类巨大的数组:
Array
(
[Ano] => Array
(
[0] => stdClass Object
(
[blog_id] => 1
[site_id] => 1
[domain] => www.my-domain.dch
[path] => /another-blog-path/
[spam] => 0
[deleted] => 0
[blogname] => Another Company
[siteurl] => http://www.my-domain.dch/another-blog-path
),
[0] => stdClass Object
(
[blog_id] => 2
[site_id] => 1
[domain] => www.my-domain.dch
[path] => /another-user-blog-path/
[spam] => 0
[deleted] => 0
[blogname] => Another User Company
[siteurl] => http://www.my-domain.dch/another-user-blog-path
),
)
...
[Com] => Array
(
[0] => stdClass Object
(
[blog_id] => 28
[site_id] => 1
[domain] => www.my-domain.dch
[path] => /my-blog-path/
[spam] => 0
[deleted] => 0
[blogname] => Company Name
[siteurl] => http://www.my-domain.dch/my-blog-path
)
)
我想实现的基本想法是获取公司名称的前三个列,并将所有匹配前三个字母的公司添加为该数组键的子项。
因此,在示例中,名称为"Company Name"
,"Commands and Order Company"
,"Comparis Masters Company"
的公司在路径$my_companies['Com'][idx]->blogname
下可用。
那么,为了从我的服务器中使用更少的资源,最好的方法是什么?
Sidenote,可能需要使用另一个级别,在三个字母之上,使用初始公司名称作为群集的第一级。
答案 0 :(得分:2)
这只是一个示例,您可能需要处理特殊情况,例如小写或短于3 blogname
。
$values = array_reduce($array, function ($new, $value) {
$index = substr($value->blogname, 0, 3);
$new[$index][] = $value;
return $new;
}, array());
或使用foreach
$new = array();
foreach ($array as $value) {
$index = substr($value->blogname, 0, 3);
$new[$index][] = $value;
}
答案 1 :(得分:1)
您可以使用三元搜索特里。另一种方法是使用数组,例如:http://phpir.com/tag/trie。