PHP通过数值合并两个数组

时间:2019-01-05 08:11:15

标签: php arrays array-merge

我有两个数组。

$ array1

Array (
  [0] => Array (
      [time] => 100
      [text] => Hello
  )
  [1] => Array (
      [time] => 200
      [text] => World!
  )
  [3] => Array (
      [time] => 300
      [text] => Array1's There
  )
)

更多...

$ array2

Array (
  [0] => Array (
      [time] => 50
      [text] => Hello
  )
  [1] => Array (
      [time] => 150
      [text] => World!
  )
  [3] => Array (
      [time] => 300
      [text] => Array2's There
  )
)

更多...

$ desiredResult:

Array (
  [0] => Array (
      [time] => 50
      [text] => Hello
  )
  [1] => Array (
      [time] => 100
      [text] => Hello
  )
  [2] => Array (
      [time] => 150
      [text] => World
  )
  [3] => Array (
      [time] => 200
      [text] => World
  )
  [4] => Array (
      [time] => 300
      [text] => Array1's There
  )
  [5] => Array (
      [time] => 300
      [text] => Array2's There
  )
)

我需要按时间的数值合并两个数组,如果时间的值相同,则首先合并Array1的数据。

1 个答案:

答案 0 :(得分:1)

使用以下代码,您将获得所需的结果。

$finalArray = array();
if(count($array1) == count($array2)){
  for ($icount = 0; $icount < count($array1); $icount++) {
    if( ($array1[$icount] < $array2[$icount]) || ($array1[$icount] == $array2[$icount])){
      $finalArray[] = $array1[$icount];
      $finalArray[] = $array2[$icount];
    } else if($array1[$icount] > $array2[$icount]){
      $finalArray[] = $array2[$icount];
      $finalArray[] = $array1[$icount];
    }
  }
}

我还创建了一个函数,如果有人数组比其他数组包含更多的值,该函数可以为您提供结果。

function mapArray($array1, $array2, $minCount, $maxCount, $maxCountFrom = ''){
  for ($icount = 0; $icount < $minCount; $icount++) {
    if( ($array1[$icount] < $array2[$icount]) || ($array1[$icount] == $array2[$icount])){
      $finalArray[] = $array1[$icount];
      $finalArray[] = $array2[$icount];
    } else if($array1[$icount] > $array2[$icount]){
      $finalArray[] = $array2[$icount];
      $finalArray[] = $array1[$icount];
    }
  }

  if(!empty($maxCountFrom)){
    if($maxCountFrom == '1'){
      for ($jcount = $icount; $jcount < $maxCount; $jcount++) {
        $finalArray[] = $array1[$jcount];
      }
    } else if($maxCountFrom == '2'){
      for ($jcount = $icount; $jcount < $maxCount; $jcount++) {
        $finalArray[] = $array2[$jcount];
      }
    }
  }
  return $finalArray;
}

$array1Count = count($array1);
$array2Count = count($array2);
if($array1Count > $array2Count){
  $result = mapArray($array1, $array2, $array2Count, $array1Count, '1');
} elseif($array1Count < $array2Count){
  $result = mapArray($array1, $array2, $array1Count, $array2Count, '2');
} elseif($array1Count == $array2Count){
  $result = mapArray($array1, $array2, $array2Count, $array2Count);
}

在此函数中,您可以通过2 array个计数和count of the both array个计数传递minimummaximum,最后一个参数是定义哪个array has maximum value和从哪个{该数组将所有剩余值提取到final array