1

How could I get the keys from a dynamic multidimensional arrays those I randomized them using Shuffle function?

Assume that I have this script:

    function customShuffle(array &$array) {
    $firstElement = array_shift($array);
    shuffle($array);
    array_unshift($array, $firstElement);
}

$array = array(
  'row_1' => array("Bird", "Brown", "Bear", "Bangkok", "Bat"),
  'row_2' => array("Carrot", "Cat", "Crispy", "Cross", "Cable"),
  'row_3' => array("All", "Apple", "Adam", "Apart", "Air")
);

array_walk($array, function (&$array) { customShuffle($array); });

Shuffle($array);

That script would give me a shuffled arrays vertically and shuffled elements in each array.

I tried to use array_keys function, but it keep giving me the main array keys only!

What I need is to get the dynamic keys for every element in every sub array, as well as the keys of the dynamic arrays in the first level, how could I do that, please?

Access Denied
  • 224
  • 1
  • 14
MRAN
  • 127
  • 2
  • 12

2 Answers2

2

It's easy :) the array_walk callback expects two params: the value and the key:

array_walk($array, function ($val, $key) { ... });
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I see, but I added a missed information, would you review your answer, please? – MRAN May 25 '13 at 13:54
  • Would you please check the update, and it will explain exactly what I am expecting. Thank you. – MRAN May 25 '13 at 14:15
  • @MRAN I need to be AFK for a while. But I'll have a look later here (but it can take a while) . – hek2mgl May 25 '13 at 14:18
  • I have read the question again. The CustomShuffle makes no sense for me. Can you tell me what will you originally achieve? – hek2mgl May 25 '13 at 23:43
  • @hek2mgl: I need to get informed with every change in positions for the arrays and the subarrays’ elements. This CustomShuffle provided me with the requested shuffle for the elements in every subarray, as well as the subarrays, but I couldn't find the way to get the positions changes for the elements and the subarrays themselves! – MRAN May 27 '13 at 15:50
1

Use array_map .. the keys would be intact

$array = array_map(function ($v) {
    shuffle($v);
    return $v;
}, $array);

Sub array keys

$keys = array_map(function ($v) {
    return array_keys($v);
}, $array);
Baba
  • 94,024
  • 28
  • 166
  • 217
  • it is working, but I have a fixed keys for the first level array in spite of they have certain keys' names! as well as the sub level arrays keys, but I the the last one because I didn't assign keys' names to them, I'll try that and come back. – MRAN May 25 '13 at 14:07
  • Thanks for your initiative :) I do have the same issue :) – MRAN May 25 '13 at 14:16