-1

two-dimensional array
need to target the subarray where key id is equal to a variable $id
and move that target array at the top of main array

$id = 2;

$rows = Array(
[0] => Array(
[id] => 1 [0] => 1
[top] => vid [1] => vid)

// target array
[1] => Array(
[id] => 2 [0] => 2 // target element
[top] => img [1] => img)

[2] => Array(
[id] => 3 [0] => 3
[top] => gall [1] => gall)
)

$target = // subarray having [id] => 2

after selecting the target, I suppose the prodedure is like this:

unset($rows[$target]);
$rows = $target + $rows;

so problem is to select the target subarray

0stone0
  • 34,288
  • 4
  • 39
  • 64
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • Does this answer your question? [How to get an array of specific "key" in multidimensional array without looping](https://stackoverflow.com/questions/7994497/how-to-get-an-array-of-specific-key-in-multidimensional-array-without-looping) – ADyson Jun 21 '21 at 12:26
  • maybe - using array_column and foreach loop, but I hope there is a way without loop – qadenza Jun 21 '21 at 12:32

1 Answers1

2

You can use usort to achieve this. The second argument allows you to provide user-defined sorting function and you can find your expected element there.

$id = 2;

$rows = array(
  0 => array(
    "id" => 1,
    "test" => 'test 0'
  ),
  1 => array(
    "id" => 2,
    "test" => 'test 1'
  ),
  2 => array(
    "id" => 3,
    "test" => 'test 2'
  )
);

$clonedRows = array_merge($rows);

usort($clonedRows, function ($a, $b) use ($id) {
  if ($a["id"] === $id) return -1;  
  return 1;
});

var_dump($clonedRows);
var_dump($rows);
choz
  • 17,242
  • 4
  • 53
  • 73