我有一个多维数组,我需要搜索一些特定的值,这里是数组:
$Array = Array
(
Array
(
'sibling' => 'Product 1',
'another_sibling' => 'not important',
'parent' => Array
(
'0' => Array
(
'product-name' => 'Placeholder name 0',
),
'1' => Array
(
'product-name' => 'Placeholder name 1',
),
'2' => Array
(
'product-name' => 'Placeholder name 2',
)
)
),
Array
(
'sibling' => 'Product 2',
'another_sibling' => 'not important',
'parent' => Array
(
'0' => Array
(
'product-name' => 'Placeholder name 3',
)
)
)
);
现在我想根据'product-name'值获得'兄弟'值,比如我有以下内容:
$RequestData = Array
(
'0' => 'Placeholder name 0',
'1' => 'Placeholder name 1',
'2' => 'Placeholder name 3',
);
我需要一个函数来取$RequestData
并在$array
内搜索'sibiling'值,然后返回如下内容:
产品1
占位符名称0
占位符名称1
产品2
我能够做这样的事情,但它会为每个项目返回一个数组,我想在同一个数组下合并相同产品的项目:
function find($RequestData , $array){
foreach ($RequestData as $item) {
foreach ($array as $key => $val) {
foreach ($val['parent'] as $key0 => $val0) {
if ($val0['product-name'] == $item) {
$result[] = array(
'product' => $val['sibling'],
'items' => array (
$item,
),
);
}
}
}
}
return $result;
}
答案 0 :(得分:1)
尝试此功能:
function find($RequestData, $array)
{
$result = [];
$elementsReq = count($RequestData);
foreach ($array as $value)
{
$curProd = $value['sibling'];
$elem = [];
foreach ($value['parent'] as $parent)
{
for ($i=0; $i < $elementsReq; $i++)
{
if($parent['product-name'] == $RequestData[$i])
{
array_push($elem, $RequestData[$i]);
break;
}
}
}
$curProdArray = array
(
'sibling' => $curProd,
'products-name' => $elem
);
array_push($result, $curProdArray);
}
return $result;
}
这将以print_r(find($RequestData, $rray));
Array
(
[0] => Array
(
[sibling] => Product 1
[products-name] => Array
(
[0] => Placeholder name 0
[1] => Placeholder name 1
)
)
[1] => Array
(
[sibling] => Product 2
[products-name] => Array
(
[0] => Placeholder name 3
)
)
)