我需要你的帮助,我有一个如下所示的数组
[["A","Orange"],["B","Orange"],["C","Orange"],["D","Orange"],["E","Apple"],["F","Mango"],["G","Banana"]]
我想找到相同的水果,结果就是
A - D: Orange, E: Apple, F: mango, G Banana
如何在多个阵列中搜索相同的水果?感谢。
答案 0 :(得分:1)
使用水果名称作为键,将键作为结果的值。
foreach($fruits as $fruit)
{
$o[$fruit[1]][] = $fruit[0];
}
测试代码:
<?php
$fruits = [["A","Orange"],["B","Orange"],["C","Orange"],["D","Orange"],["E","Apple"],["F","Mango"],["G","Banana"]];
foreach($fruits as $fruit)
{
$o[$fruit[1]][] = $fruit[0];
}
var_dump($o);
输出:
ei@localhost:~$ php test.php
array(4) {
["Orange"]=>
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "C"
[3]=>
string(1) "D"
}
["Apple"]=>
array(1) {
[0]=>
string(1) "E"
}
["Mango"]=>
array(1) {
[0]=>
string(1) "F"
}
["Banana"]=>
array(1) {
[0]=>
string(1) "G"
}
}
编辑:
<?php
$fruits = [["A","Orange"],["B","Orange"],["C","Orange"],["D","Orange"],["E","Apple"],["F","Mango"],["G","Banana"]];
$fruits2 = [["A","Orange"],["C","Orange"],["D","Orange"],["E","Apple"],["F","Mango"],["G","Banana"]];
foreach($fruits2 as $fruit)
{
$o[$fruit[1]][] = $fruit[0];
}
$o = array_map(function($v){
$str = '';
$pre = '';
$isInSequence = false;
$item = '';
foreach($v as $item)
{
if($pre != '')
{
if(ord($pre) == ord($item) - 1)
{
$isInSequence = true;
}
else
{
if($isInSequence)
$str = $str . '-';
else
$str = $str . ',' . $item;
$isInSequence = false;
}
}
else
$str = $str.$item;
$pre = $item;
}
if($isInSequence)
{
$str = $str . '-' . $item;
}
return $str;
}, $o);
var_dump($o);
输出:
ei@localhost:~$ php test.php
array(4) {
["Orange"]=>
string(5) "A,C-D"
["Apple"]=>
string(1) "E"
["Mango"]=>
string(1) "F"
["Banana"]=>
string(1) "G"
}