简体   繁体   English

在PHP中合并二维数组

[英]Merge two-dimensional arrays in PHP

I have two two-dimensional arrays (actually they are nested associative arrays) with predefined struture: $array1 and $array2 . 我有两个二维数组(实际上它们是嵌套的关联数组),带有预定义的结构: $array1$array2 First array lists all objects by their id numbers: 第一个数组按其ID号列出所有对象:

$array1 = array(
    array(id => 1),
    array(id => 2),
    array(id => 3),
    array(id => 4),
    array(id => 5)
);

The second array lists relationships between objects (eg, object 2 is connected to objects 3, 4, and 5): 第二个数组列出了对象之间的关系(例如,对象2连接到对象3,4和5):

$array2 = array(
    array(id1 => 1, id2 => 2),
    array(id1 => 2, id2 => 3),
    array(id1 => 2, id2 => 4),
    array(id1 => 2, id2 => 5)
);

The aim is to replace id values from the $array2 with corresponding indices from $array1 . 目的是将$array2 id值替换为$array1相应索引。 So, in my case the result should be: 所以,在我的情况下,结果应该是:

0 1 // index of value 1 (id1) in $array1 is 0, index of 2 (id2) is 1
1 2
1 3
1 4

Pasted below is my current work. 下面粘贴的是我当前的工作。 First of all I "convert" $array1 to one-dimensional array: 首先,我将$array1转换为一维数组:

foreach ($array1 as $row) {
    $array3[] = $row['id'];
}

Then I use array_search function and go through $array2 and search the $array3 for a given value and returns the corresponding key in $array3 : 然后,我使用array_search函数并通过$array2并在$array3搜索给定值,并在$array3返回相应的键:

foreach ($array2 as $row) {
  $value1 = $row['id1'];
  $key1 = array_search($value1, $array3);
  echo $key1;
  echo "\t";
  $value2 = $row['id2'];
  $key2 = array_search($value2, $array3);
  echo $key2;
  echo '<br />';
}

My question is straightforward: is there a more elegant way to do that (ie, without using array_search function). 我的问题很简单:是否有更优雅的方法(即不使用array_search函数)。

Many thanks in advance for any ideas. 非常感谢您的任何想法。

Best, Andrej 最好的,安德烈

You can use an associative array that associates the value to the index. 您可以使用将值关联到索引的关联数组。

foreach ($array1 as $index => $row) {
    $array3[$row['id']] = $index;
}

Then you can 那么你也能

$key1 = $array3[$value1];

and

$key2 = $array3[$value2];

if each row in $array1 have an unique id, you can flip the $array3 如果$array1中的每一行都有一个唯一的ID,则可以翻转$array3

<?php
$array3 = array();
foreach ($array1 as $k => $v) {
    $array3[$v['id']] = $k;
}
foreach ($array2 as $row) {
    list($id1, $id2) = $row;
    printf("%s\t%s<br />",  $array3[$id1], $array3[$id2]); 
}

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

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