0

I am using the following hook_views_pre_render to merge 2 views_data_export views.

function hook_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'commerce_orders' && $view->current_display == 'data_export_1') {
    $first_extra_results_view = Views::getView('commerce_orders');
    $first_extra_results_view->setDisplay('data_export_2');
    $first_extra_results_view->execute();
    $first_extra_results_view->result;
    $view->result = array_merge($view->result, $first_extra_results_view->result);

  }
}

Both of the views are sorted by order_number, but array_merge is just stacking them on one another (as expected).

$view order_1
$view order_2
$first_extra_results_view order_1
$first_extra_results_view order_2

I would like to know how to take the new $view->result and re-apply the sort criteria so that the output of the $view->result would be this:

$view order_1
$first_extra_results_view order_1
$view order_2
$first_extra_results_view order_2

I am able to get the order number for each result, but I don't know how to sort the view results by those order numbers:

foreach ($results as $key => $value) {
  $order_number = $value->commerce_order_order_number;
}

1 Answer 1

1

I was able to work this out quite simply. I put the array_merge() into a $results variable:

$results = array_merge($view->result, $first_extra_results_view->result);

To get the $order_number for each of the $results, I used array_column():

$order_number = array_column($results, 'commerce_order_order_number');

Then to sort the $results by $order_number I used array_multisort().:

array_multisort($order_number, SORT_DESC, $results);

I did also have to re-sort the entire array for some reason, but all in all this is what I came up with:

function hook_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'commerce_orders' && $view->current_display == 'data_export_1') {
    $first_extra_results_view = Views::getView('commerce_orders');
    $first_extra_results_view->setDisplay('data_export_2');
    $first_extra_results_view->execute();
    $first_extra_results_view->result;
    $results = array_merge($view->result, $first_extra_results_view->result);

    // Sort the rows by order number.
    $order_number = array_column($results, 'commerce_order_order_number');
    array_multisort($order_number, SORT_DESC, $results);

    // Sort the rows so that shipping items are back on the bottom.
    krsort($results);
    $view->result = $results;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.