S
S
Shimpanze2020-02-07 07:55:30
JavaScript
Shimpanze, 2020-02-07 07:55:30

How to sort such elements in PHP?

Hello!

There is an example design:

<ul>
   <li>Конфеты</li>
   <li>Пряники</li>
   <li>Асфальт</li>
</ul>


You need to sort them like this (in the required order):

<ul>
   <li>Пряники</li>
   <li>Асфальт</li>
   <li>Конфеты</li>
</ul>


Now I do something like this:

$category_name;
$accumulation;

foreach( $elements as $element ) {
  $category_name = preg_split( '/\n/', $element->textContent, -1, PREG_SPLIT_NO_EMPTY );

  if ( mb_stripos( $category_name[0], 'Пряники' ) !== false ) {
    $accumulation .= $element->ownerDocument->saveHTML( $element );
    continue;
  }
  else if ( mb_stripos( $category_name[0], 'Асфальт' ) !== false ) {
    $accumulation .= $element->ownerDocument->saveHTML( $element );
    continue;
  }
  else if ( mb_stripos( $category_name[0], 'Конфеты' ) !== false ) {
    $accumulation .= $element->ownerDocument->saveHTML( $element );
    continue;
  }
}

echo $accumulation;


But the order doesn't change at all. Why?

Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ruslan Ruslanov, 2019-05-24
@tosster22

null !== undefined
, you can split the code into different files and include it where necessary.
you can check for undefined.
if (btns[0]!== null && btns[0] !== undefined) {

A
AUser0, 2020-02-07
@Shimpanze

<?php
function my_sorting($in, $sort)
{
    $tmp = array();
    foreach ($sort as $k => $v) $tmp[$k] = "";
    foreach ($in as $v) ($t = array_search($v, $sort)) !== false ? $tmp[$t] .= $v."\n" : $tmp[] = $v."\n";
    return implode("", $tmp);
}

$arr = array("Асфальт", "Карапуз", "Конфеты", "Пряники");
var_dump(my_sorting($arr, array("Пряники", "Асфальт", "Конфеты")));

S
Stalker_RED, 2020-02-07
@Stalker_RED

Because in what order you got them, you insert them in, and it doesn't matter which if worked.
As an option - put them in an array and apply one of the sort functions .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question