Как изменить позицию элемента в массиве? - PullRequest
0 голосов
/ 28 мая 2020

У меня есть проект в Laravel 5. Проект работает нормально, но у меня проблема с позицией сортировки в моем массиве. У меня есть массив с неправильным идентификатором позиции и адресом электронной почты:

Array
(
    [0] => Array
        (
            [0] => sda@swqdqwdwq.pll
            [1] => 957
            [2] => xxxx
            [3] => xxxx
            [4] => xxxx
            [5] => 2021-01-19
            [6] => tak
            [7] => 
<a href="http://projekt2.test/admin/client/info/957" class="btn btn-xs blue get-info ">
    <i class="fa fa-search"></i>
     Przeglądaj
</a>
<a href="http://projekt2.test/admin/client/edit/957" class="btn btn-xs blue ">
    <i class="fa fa-pencil"></i>
     Edytuj
</a>
<a href="http://projekt2.test/admin/client/delete/957" class="btn btn-xs red delete">
    <i class="fa fa-trash-o"></i>
     Usuń
</a>
<a href="http://projekt2.test/admin/client/deactive/957" class="btn btn-xs yellow">
    <i class="fa fa-ban"></i>
     Dezaktywuj
</a>

        )

    [1] => Array
        (
            [0] => xxxx@op.pl
            [1] => 958
            [2] => xxxx
            [3] => xxxx
            [4] => firmowe
            [5] => 2021-02-03
            [6] => tak
            [7] => 
<a href="http://projekt2.test/admin/client/info/958" class="btn btn-xs blue get-info ">
    <i class="fa fa-search"></i>
     Przeglądaj
</a>
<a href="http://projekt2.test/admin/client/edit/958" class="btn btn-xs blue ">
    <i class="fa fa-pencil"></i>
     Edytuj
</a>
<a href="http://projekt2.test/admin/client/delete/958" class="btn btn-xs red delete">
    <i class="fa fa-trash-o"></i>
     Usuń
</a>
<a href="http://projekt2.test/admin/client/deactive/958" class="btn btn-xs yellow">
    <i class="fa fa-ban"></i>
     Dezaktywuj
</a>

        )
...
}

Мой php код:

$data = $this->getList();
print_r($data);

Мне нужно изменить идентификатор позиции и адрес электронной почты (идентификатор первой позиции, второй адрес электронной почты). Мне нужен результат:

Array
    (
        [0] => Array
            (
                [0] => 957 
                [1] => sda@swqdqwdwq.pll
                [2] => xxxx
                [3] => xxxx
                [4] => xxxx
                [5] => 2021-01-19
                [6] => tak
                [7] => 
    <a href="http://projekt2.test/admin/client/info/957" class="btn btn-xs blue get-info ">
        <i class="fa fa-search"></i>
         Przeglądaj
    </a>
    <a href="http://projekt2.test/admin/client/edit/957" class="btn btn-xs blue ">
        <i class="fa fa-pencil"></i>
         Edytuj
    </a>
    <a href="http://projekt2.test/admin/client/delete/957" class="btn btn-xs red delete">
        <i class="fa fa-trash-o"></i>
         Usuń
    </a>
    <a href="http://projekt2.test/admin/client/deactive/957" class="btn btn-xs yellow">
        <i class="fa fa-ban"></i>
         Dezaktywuj
    </a>

            )

Как его сделать? У меня есть старый проект Laravel 5.

Помогите, пожалуйста

Ответы [ 2 ]

0 голосов
/ 28 мая 2020

Попробуйте:

<?php

$arr = ['foo', 'foobar@gmail.com', 'myName', 'myInfo', 954];
$arrMask = ['/\d+/', '/\w+@\w+.\w+/', '/*/', '/*/', '/*/'];

print_r(sortArrayByExp($arr, $arrMask));

/**
 * Sort a array by RegExp
 * 
 * Sort a array by regular expression
 * 
 * @param   array   $arr        Array to sort
 * @param   array   $arrRegExp  Array to postion Regex
 * 
 * @return  array   Return a new array mirrored by value in $arrRegExp
 * 
 * @throws  \InvalidArgumentException
 */
function sortArrayByExp($arr, $arrRegExp)
{

    if(! is_array($arr))
        throw new \InvalidArgumentException('Value in parameter $arr must be array!', 556);

    if(! is_array($arrRegExp))
        throw new \InvalidArgumentException('Value in parameter $arrRegExp must be array!', 557);


    $newArray = [];

    foreach($arrRegExp as $key => $mask)
    {
        if(! is_string($mask))
            throw new \InvalidArgumentException('Each value in $arrRegExp must be string or RegExp', 558);

        $response = null;
        if(@preg_match($mask, '') !== false)
        {
            foreach($arr as $posArray => $value)
                if(preg_match($mask, $value))
                {
                    $response = $value;
                    unset($arr[$posArray]);
                    break;
                }

        }

        if($response !== null)
           $newArray[$key] = $response;

    }

    return $newArray;
}

/* output must be:
    Array
    (
        [0] => 954
        [1] => foobar@gmail.com
        [2] => foo
        [3] => myName
        [4] => myInfo
    )
*/

Эта функция сортирует массив по каждому значению в новом массиве, который содержит regular expression, попробуйте мой пример здесь

Изменить 1:

Вы также можете использовать collect из Laravel для сортировки массива, например:

<?php
require "vendor/autoload.php";

$myCollect = collect(['foo', 'foobar@gmail.com', 'myName', 'myInfo', 954]);

print_r($myCollect->sort(function($above, $below)
{
    $belowIsId = is_numeric($below);
    $aboveIsId = is_numeric($above);
    $belowIsMail = preg_match('/\w+@\w+.[\w\.]+/', $below);
    $aboveIsMail = preg_match('/\w+@\w+.[\w\.]+/', $above);

    $pos = 0;
    if($belowIsId)
        $pos = 1;
    elseif($belowIsMail)
        $pos = 1;
    elseif($aboveIsId || $aboveIsMail)
        $pos = -1;

    return $pos;

})->toArray());

/* output must be:
    Array (
        [4] => 954
        [1] => foobar@gmail.com
        [0] => foo
        [2] => myName
        [3] => myInfo
    )
*/

См. Подробнее, как использовать метод sort здесь , но посмотрите, что ключи сохранены, идентификатор первый, но ваш ключ в массиве все тот же

0 голосов
/ 28 мая 2020

С помощью этого кода вы можете l oop свой массив и изменить положение первых двух элементов:

foreach ($array as $subArray) {
    $tmp = $subArray[0];
    $subArray[0] = $subArray[1];
    $subArray[1] = $tmp;
}
...