0

I have two two-dimensional arrays (actually they are nested associative arrays) with predefined struture: $array1 and $array2. First array lists all objects by their id numbers:

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

The second array lists relationships between objects (e.g., object 2 is connected to objects 3, 4, and 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. 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:

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:

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 (i.e., without using array_search function).

Many thanks in advance for any ideas.

Best, Andrej

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

1

if each row in $array1 have an unique id, you can flip the $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]); 
}

1 Comment

Thanks; nice solutions using list function in the second loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.