V
V
Vadim Stepanenko2019-08-10 18:42:45
PHP
Vadim Stepanenko, 2019-08-10 18:42:45

Rearranging elements in a multidimensional array?

Hello everyone
There is a task: a multidimensional array is given as an input; position of the Nth element; the position where the element should be moved.
I broke my whole head already, maybe someone has a working algorithm?
Tried like this:

$p1 = array_splice($temp, $posTo, 1);
$p2 = array_splice($temp, 0, $posFrom);
$temp = array_merge($p2,$p1,$temp);

but it just swaps two elements,
tried to separate it into "transfer up" and "transfer down", but something always doesn't work

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VicTHOR, 2019-08-10
@Vadim1899

$games = [
    ['a0', 'b0', 'c0'],
    ['a1', 'b1', 'c1'],
    ['a2', 'b2', 'c2'],
    ['a3', 'b3', 'c3'],
    ['a4', 'b4', 'c4']
];

$elemPos = 4;
$elemNeededPos = 1;

$new[$elemNeededPos] = $games[$elemPos];

foreach ($games as $k => $v) {
    //отсекли то, что уже забрали
    if ($k == $elemPos) continue;
    //отсекли то, что не нужно двигать
    if ($k > $elemPos && $k > $elemNeededPos || $k < $elemPos && $k <$elemNeededPos) {
        $new[$k] = $games[$k];
    } elseif ($elemPos > $elemNeededPos) {
        $new[$k + 1] = $games[$k];
    } elseif ($elemPos < $elemNeededPos) {
        $new[$k - 1] = $games[$k];
    }
}
ksort($new);

print_r($new);

tests

A
Andrey, 2019-08-10
@VladimirAndreev

<?php

$content = [
  0 => [10,15,20],
  1 => [10,20,15],
  2 => [15,10,20],
  3 => [15,20,10],
  4 => [20,10,15],
  5 => [20,15,10],
];

$a = 1;
$b = 5;

echo json_encode($content), PHP_EOL, sprintf('$a=%d, $b=%d', $a, $b), PHP_EOL;

$raw_a = array_slice($content, 0, $a); // часть массива до $a
$raw_b = array_slice($content, $a+1, $b-$a-1); // часть массива между $a и $b
$raw_c = array_slice($content, $b+1); // часть массива после $b

// echo json_encode(['a'=>$raw_a, 'b'=>$raw_b, 'c'=>$raw_c]), PHP_EOL;

$result = array_merge($raw_a, [$content[$b]], $raw_b, [$content[$a]], $raw_c);

echo json_encode($result), PHP_EOL;

how to do it if $b < $a - think for yourself =) there is a frontal option - [$a, $b] = [$b, $a] and array_reverse on $content twice (before and after the substitution).. maybe you can do it nicely =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question