简体   繁体   English

通过ID合并两个PHP数组

[英]Merge two PHP array by ID

I have two array get from two foreach loop. 我有两个数组从两个foreach循环中获取。

Array ([0] => Young Boys [1] => Vidi FC [2] => Ajax [3] => Independiente)

Array ([0] => Dinamo Zagreb [1] => AEK Athens [2] => Dynamo Kyiv [3] => Santos FC)

PHP CODE PHP代码

foreach($html->find('.col-home a') as $element)  
    $array1[] = $element->plaintext;

foreach($html->find('.col-guest a') as $element2)  
    $array2[] = $element2->plaintext;

How can I get this results? 如何获得此结果?

Young Boys - Dinamo Zagreb
Vidi FC - AEK Athens
Ajax - Dynamo Kyiv
Independiente - Santos FC

thanks! 谢谢!

Loop with a for loop through one array and use the index to access the other and combine them in a result array. 使用for循环遍历一个数组,并使用索引访问另一个数组并将它们组合到结果数组中。

https://3v4l.org/jkhpK https://3v4l.org/jkhpK

$a1 = ['Young Boys', 'Vidi FC', 'Ajax', 'Independiente'];
$a2 = ['Dinamo Zagreb', 'AEK Athens', 'Dynamo Kyiv', 'Santos FC'];
$result = [];
for($i = 0; $i < count($a1); $i++) {
    $result[] = $a1[$i] . ' - ' . $a2[$i];
}

var_dump($result);

Output for 5.6.30, hhvm-3.18.5 - 3.22.0, 7.0.28 - 7.3.0beta2 5.6.30,hhvm-3.18.5-3.22.0、7.0.28-7.3.0beta2的输出

array(4) {
  [0]=>
  string(26) "Young Boys - Dinamo Zagreb"
  [1]=>
  string(20) "Vidi FC - AEK Athens"
  [2]=>
  string(18) "Ajax - Dynamo Kyiv"
  [3]=>
  string(25) "Independiente - Santos FC"
}

EDIT: You might aswell add an isset check in the loop to make sure you don't access an index that is not available in the 2nd array like 编辑:您还可以在循环中添加一个isset检查,以确保您不会访问第二个数组中不可用的索引,例如

for($i = 0; $i < count($a1); $i++) {
    if(isset($a1[$i]) && isset($a2[$i])) { 
        $result[] = $a1[$i] . ' - ' . $a2[$i];
    }
}

Go through one array and find item from the other with the same index: 遍历一个数组,从另一个数组中查找具有相同索引的项目:

foreach ($array1 as $index => $val1)
    echo $val1.' - '.$array2[$index].'<br />';

If You are not sure that the arrays are of the same length, You can use the longer (or shorter) one: 如果不确定数组的长度相同,则可以使用更长(或更短)的数组:

$count = max(count($array1), count($array2));
for ($i = 0; $i < $count; $i++)
    echo (isset($array1[$i])?$array1[$i]:'').' - '.(isset($array2[$i])?$array2[$i]:'').'<br />';

EDIT: Used isset() instead of @ , thanks to @Xatenev's comment. 编辑:感谢@Xatenev的评论,而不是@使用isset()

try this 尝试这个

 $a = array( 'Young Boys' ,'Vidi FC' , 'Ajax' , 'Independiente');
   $b = array( 'Dinamo Zagreb', 'AEK Athens', 'Dynamo Kyiv', 'Santos FC');
   foreach ($a as $key => $val){
   echo $val.' - '.$b[$key];
   echo '<br />'; 
   }  

Take longest Array in foreach. 在foreach中使用最长的数组。

foreach($array2 as $k =>$v){    
    $concrat[$v] = $array1[$k];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM