加入像SQL这样的多维数组 [英] Join multidimensional array like SQL
本文介绍了加入像SQL这样的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数组. parentId
键很重要!
I have following array. parentId
key important!
Array
(
[0] => Array
(
[id] => 1
[name] => Home
[parentId] =>
[children] =>
)
[1] => Array
(
[id] => 2
[name] => About
[parentId] =>
[children] =>
)
[2] => Array
(
[id] => 3
[name] => Services
[parentId] => 2
[children] =>
)
)
下面是我的expected
数组结果.您会看到Services
在About
下,其ID为2
,服务parentId为2
And below is my expected
array result. You'll see the Services
is is under the About
that have id is 2
and services parentId is 2
Array
(
[0] => Array
(
[id] => 1
[name] => Home
[parentId] =>
[children] =>
)
[1] => Array
(
[id] => 2
[name] => About
[parentId] =>
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => Services
[parentId] => 2
[children] =>
)
)
)
)
我可以使用array_walk
或array_map
和foreach
轻松地做到这一点.
I can do this with array_walk
or array_map
and foreach
easily.
我只是想知道是否有任何function
可以在没有foreach loop
的情况下连接像SQL JOIN这样的数组索引?
I just wonder that is there any function
that join array indexes like SQL JOIN without foreach loop
?
所以在我的数组中:id = parentId
推荐答案
尝试该库
https://github.com/erdalceylan/array-join
https://github.com/erdalceylan/array-join
数据
$users = [
["id"=>1, "nick"=>"erdal"],
(object)["id"=>2, "nick"=>"furkan" ],
["id"=>3, "nick"=>"huseyin"],
["id"=>4, "nick"=>"hümeyra" ],
["id"=>5, "nick"=>"tuba" ],
];
$items = [
["user_id"=>1, "item"=>"kaban", "mmx" => "mmx1"],
["user_id"=>1, "item"=>"çorap", "mmx" => "mmx2"],
["user_id"=>1, "item"=>"çorap", "mmx" => "mmx3"],
(object)["user_id"=>1, "item"=>"çorap", "mmx" => "mmx4"],
["user_id"=>1, "item"=>"çorap", "mmx" => "mmx5"],
["user_id"=>1, "item"=>"çorap", "mmx" => "mmx6"],
["user_id"=>2, "item"=>"araba", "mmx" => "mmx7"],
(object)["user_id"=>9, "item"=>"ev", "mmx" => "mmx8"],
["user_id"=>10, "item"=>"yat", "mmx" => "mmx9"],
];
$foods = [
["user_id"=>1, "food"=>"iskender"],
["user_id"=>2, "food"=>"adana"],
];
$texts = [
["user_id"=>1, "text"=>"merhaba"],
["user_id"=>15, "text"=>" hi"],
];
用法
$instance = \ArrayJoin\Builder::newInstance()
->select("a.id", "a.nick", "b.item", "d.food")
->from($users, "a")
->innerJoin($items, "b", new \ArrayJoin\On("a.id = b.user_id"))
->leftJoin($texts, "c", new \ArrayJoin\On("a.id = c.user_id"))
->rightJoin($foods, "d", new \ArrayJoin\On("b.user_id = d.user_id"))
->where("a.id", "a.text", function ($fieldFirs, $fieldSecond){
return $fieldFirs < 10;
})
->limit(2)
->offset(1)
->setFetchType(\ArrayJoin\Builder::FETCH_TYPE_OBJECT);
$instance->execute();
输出
array (
stdClass::__set_state(array(
'id' => 1,
'nick' => 'erdal',
'item' => 'çorap',
'food' => 'iskender',
)),
stdClass::__set_state(array(
'id' => 1,
'nick' => 'erdal',
'item' => 'çorap',
'food' => 'iskender',
)),
)
这篇关于加入像SQL这样的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文