Home > OS >  Reorder and preserve php array based on given keys
Reorder and preserve php array based on given keys

Time:03-29

wondering if it's possible to reorder a php array based on given keys, currently I have an array that looks like this:

array:4 [▼
  0 => array:3 [▼
    "to" => "test"
    "name" => "name"
    "type" => "custom"
  ]
  1 => array:4 [▼
    "to" => "test 2"
    "name" => "name 2"
    "type" => "page"
    "target" => "test"
  ]
  2 => array:4 [▼
    "to" => "my link"
    "name" => "something"
    "type" => "custom"
    "target" => "_blank"
  ]
  3 => array:4 [▼
    "to" => "https://github.com/"
    "name" => "github"
    "type" => "custom"
    "target" => "_parent"
  ]
]

On the frontend I'm using sortableJs to allow users to reorder the items to their liking, when the onSort event is fired I collect all of the ids inside of the sortable container and send it to the php function.

the data that sortable send looks like this

array:4 [▼
  0 => "0"
  1 => "2"
  2 => "1"
  3 => "3"
]

Where the value is the order that they're supposed to be in, so based on this data the original array would need to be this

array:4 [▼
  0 => array:3 [▼
    "to" => "test"
    "name" => "name"
    "type" => "custom"
  ]
  2 => array:4 [▼
    "to" => "my link"
    "name" => "something"
    "type" => "custom"
    "target" => "_blank"
  ]
  1 => array:4 [▼
    "to" => "test 2"
    "name" => "name 2"
    "type" => "page"
    "target" => "test"
  ]
  3 => array:4 [▼
    "to" => "https://github.com/"
    "name" => "github"
    "type" => "custom"
    "target" => "_parent"
  ]
]

I've been thinking about this but can't seem to figure it out.

CodePudding user response:

Oh, I love these! My solution would be

$sorted_array = array_map(
    function($index) use ($original_array){
        return $original_array[$index];
    },
    $sort_order
);

Where $original_array is your original array and $sort_order is the data that sortable sends.

EDIT: This only shuffles the values around, it does not conserve the keys. Your array is not an associative array, and your keys are not in fact keys but indices, and will always be displayed in order.

CodePudding user response:

I think something like this would help

$original // your original array
$sortable // your returned array;
$i = 0;
foreach ($sortable as $key=>$value) { // where value is the new key
$newArrayOrder[] = array($value[$i] => $original[$i]);
$i  ;
}
  • Related