1

I would like to map values in two arrays which have different shapes, as follows:

$array1=array(
    1=>array(1=>'apple', 2=>'banana', 3=>'cherry'),
    2=>array(1=>'david', 2=>'eddie', 3=>'frank'),
);

Now:

$array2=array(
    1=>'apple',
    2=>'banana',
    3=>'cherry',
    4=>'david',
    5=>'eddie',
    6=>'frank',
);

Such that when the value of $array1[2][3] is changed from frank to paula for example, then the value of $array2[6] is changed similarly.

How would I do this? NOTE: the keys will not change in quantity once declared.

2
  • 2
    If you want to keep the two array structures in sync, then you'll have to rebuild $array2 whenever $array1 changes. One could use references, but that would require manual array building. A virtual ArrayObject that automaps it might be another option. Commented Apr 7, 2015 at 9:00
  • @SunilPachlangia, array_merge will not sync things Commented Apr 8, 2015 at 20:44

3 Answers 3

1

Do you have the freedom to build the $array2 in another way? If you do, then this is how you can go about the 'linked' arrays:

<?php

$array1=array(
    1=>array(1=>'apple', 2=>'banana', 3=>'cherry'),
    2=>array(1=>'david', 2=>'eddie', 3=>'frank'),
);
$array2=array(
    1=>'apple',
    2=>'banana',
    3=>'cherry',
    4=>'david',
    5=>'eddie',
    // Assign by reference $array1[2][3] (currently holding 'frank')
    6=>&$array1[2][3],
);
// This will print the initial state of $array2
echo '<pre>';print_r( $array2 );echo '</pre>';
// Now change the value in $array1
$array1[2][3] = 'paula';
// And since $array2 'points' to the same memory location it will get
// changed too (well technically it won't but that's not important)
echo '<pre>';print_r( $array2 );echo '</pre>';

For more information about assignment by reference you can check this out

Sign up to request clarification or add additional context in comments.

Comments

1

Please use array merge, here is how it will help you.

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

will output,

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

to learn more, http://php.net/manual/en/function.array-merge.php

Comments

1
<?php


$array1=array(
    1=>array(1=>'apple', 2=>'banana', 3=>'cherry'),
    2=>array(1=>'david', 2=>'eddie', 3=>'frank'),
);
$op = array();

foreach($array1 as $key =>$index){
    $op =array_merge($array1[1],$array1[2]);
}

print_r(  $op);
?>

Use array_merge to merge two arrays

1 Comment

that is not very useful. It is hard coded to 1 and 2, and merging wouldn't create an array which changes as the first one did. @mrun post is correct.

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.