Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
$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);
<?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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question