简体   繁体   中英

Order array based on another array's values

I am currently trying to order an array based on the value of another array. The values are unique. I seen examples of how to order an array based on the keys of another array but I cant seem to find one that specifically orders an array by the value of another array. Both arrays have the same values. One array has an additional key id . How could I achieve that?

Array to follow order:

Array
(
[0] => Array
    (
        [src] => 2GK2VWE-ax--0
    )

[1] => Array
    (
        [src] => 13KXEXyJaM9-0
    )

[2] => Array
    (
        [src] => 138XELryjM9-0
    )
)   

Array to order:

Array
(
[0] => Array
    (
        [src] => 13KXEXyJaM9-0
        [id] => 123468
    )
[1] => Array
    (
        [src] => 138XELryjM9-0
        [id] => 15784239
    )

[2] => Array
    (
        [src] => 2GK2VWE-ax--0
        [id] => 12558456
    )
)

Desired order:

Array
(
    [0] => Array
    (
        [src] => 2GK2VWE-ax--0
        [id] => 12558456
    )

[1] => Array
    (
        [src] => 13KXEXyJaM9-0
        [id] => 123468
    )

[2] => Array
    (
        [src] => 138XELryjM9-0
        [id] => 15784239
    )
)

You don't need to sort the array. Just search the src from the "Array to order" and add the id in the original array.

$originalArray = [
    [
        'src' => '2GK2VWE-ax--0'
    ],
    [
        'src' => '13KXEXyJaM9-0'
    ],
    [
        'src' => '138XELryjM9-0'
    ]
];

$sortedArray = [
    [
        'src' => '13KXEXyJaM9-0',
        'id' => 123468
    ],
    [
        'src' => '138XELryjM9-0',
        'id' => 15784239
    ],
    [
        'src' => '2GK2VWE-ax--0',
        'id' => 12558456
    ]
];

$src = array_column($originalArray, 'src');
foreach ($sortedArray as $data) {
    if (false !== $key = array_search($data['src'], $src)) {
        $originalArray[$key]['id'] = $data['id'];
    }
}

var_dump($originalArray);

Output:

array(3) {
  [0]=>
  array(2) {
    ["src"]=>
    string(13) "2GK2VWE-ax--0"
    ["id"]=>
    int(12558456)
  }
  [1]=>
  array(2) {
    ["src"]=>
    string(13) "13KXEXyJaM9-0"
    ["id"]=>
    int(123468)
  }
  [2]=>
  array(2) {
    ["src"]=>
    string(13) "138XELryjM9-0"
    ["id"]=>
    int(15784239)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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