phparraysmapping

Access values in a flat array according to related values in another array which dictates the order of presentation


How would you write a sorting routine in PHP that would replace the values of an array's keys, with another array's key value's if the former array's key value's are out of order.

$array1 = ['section2', 'section3', 'section1'];
$array2 = ['content for section1', 'content for section2', 'content section3'];

How could I replace the values of $array1 with the corrosponding content in $array2?

So I guess what I'm asking is how can I make $array1 display the following....

content for section2
content for section3
content for section1

in that order.


Solution

  • Loop both arrays and check if the value of $array1 exists while looping $array2, if so, change the value of $array1 to the $array2 value based on the key, so you can keep the order, i.e.:

    $array1 = ['section2', 'section3', 'section1'];
    $array2 = ['content for section1', 'content for section2', 'content for section3'];
    
    foreach($array1 as $key => $value){
        foreach($array2 as $key2 => $value2){
            if(preg_match("/$value/", $value2)){
                $array1[$key] = $value2;
            }
        }
    }
    
    print_r($array1);
    

    Output:

    Array
    (
        [0] => content for section2
        [1] => content for section3
        [2] => content for section1
    )
    

    Ideone Demo