Skip to content

Instantly share code, notes, and snippets.

@webdevs-pro
Created August 29, 2023 06:41
Show Gist options
  • Save webdevs-pro/0d2756d0e2c146bcf156308c96a09b76 to your computer and use it in GitHub Desktop.
Save webdevs-pro/0d2756d0e2c146bcf156308c96a09b76 to your computer and use it in GitHub Desktop.
PHP Function to Reorder Array Elements Based on a Template Array and a Custom Comparison Key
<?php
$value = [
[
'attribute_type' => 'pa_merchant',
'pa_merchant' => [ 305 ],
],
[
'attribute_type' => 'pa_brand',
'pa_brand' => [ 692 ],
],
[
'attribute_type' => 'dt_score',
'value' => 9.9,
],
];
$new_value = [
[
'attribute_type' => 'pa_brand',
'pa_brand' => [ 692 ],
],
[
'attribute_type' => 'pa_merchant',
'pa_merchant' => [ 310 ],
],
[
'attribute_type' => 'liters',
'value' => 2,
],
[
'attribute_type' => 'dt_score',
'value' => 9.9,
],
];
function reorderArrayBasedOnTemplate( $template_array, $array_to_reorder, $comparison_key = 'attribute_type' ) {
// Check if the template array is an array
if ( ! is_array( $template_array ) ) {
return $array_to_reorder;
}
// Create an associative array for fast lookup from $template_array
$order_lookup = [];
foreach ( $template_array as $index => $item ) {
if ( isset( $item[ $comparison_key ] ) ) {
$order_lookup[ $item[ $comparison_key ] ] = $index;
}
}
// Custom sort function
usort( $array_to_reorder, function( $a, $b ) use ( $order_lookup, $comparison_key ) {
$order_a = isset( $a[ $comparison_key ], $order_lookup[ $a[ $comparison_key ] ] ) ? $order_lookup[ $a[ $comparison_key ] ] : PHP_INT_MAX;
$order_b = isset( $b[ $comparison_key ], $order_lookup[ $b[ $comparison_key ] ] ) ? $order_lookup[ $b[ $comparison_key ] ] : PHP_INT_MAX;
return $order_a - $order_b;
} );
return $array_to_reorder;
}
// Output the sorted $new_value array
?>
<pre><?php print_r( reorderArrayBasedOnTemplate( $value, $new_value, 'attribute_type' ) ); ?></pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment