2

I have a multi dimentional php array like this :

where the column "b" has 2 possible values ( x, y) and column "v" has 2 possible values ( t,f )

Array
(
[0] => Array
    (
        [a] => 6
        [b] => x
        [c] => t
    )

[1] => Array
    (
        [a] => 4
        [b] => x
        [c] => t
    )
[2] => Array
    (
        [a] => 6
        [b] => y
        [c] => f
    )

I want to rearrange the columns so that they are structured by values , in the following way.

My Question is, is there a smart way to do this using some native php functions , without looping through everything

Array(
    [value of b=x] => Array(
        [value of c=t] => Array( all ids in the array)
        [value of c=f] => Array( all ids in the array)
     )
    [value of b=y] => Array(
        [value of c=t] => Array( all ids in the array)
        [value of c=f] => Array( all ids in the array)
     )

  )         
1
  • 1
    Even if there was a native function that did exactly that, what's wrong with looping? The native function would have to loop as well behind the scenes. Commented Apr 27, 2012 at 10:24

1 Answer 1

2

I assume that by all ids in the array you mean "all the a column values in the array". In which case, this is what you want:

$result = array();

array_walk($array, function($val, $key) use (&$result) {
  $result[$val['b']][$val['c']][] = $val['a'];
});

print_r($result);

If by ids you mean the outer array indices, simply change $val['a'] to $key in the above code.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd just go with a foreach instead of array_walk, it's really the same thing in different disguise.
@deceze I know and I agree 100%, especially since a lot of the world still runs on <5.3 (no closures) and it makes scoping much easier to cope with, but he asked for a native function implementation, so a native function implementation he shall have. One point about that which someone made to me recently though is that (if you're of a micro-optimisation disposition) a C++ loop is more efficient than a PHP loop.
I'd agree that the C++ loop is faster, but wonder if that isn't negated by the function call overhead...
thanks Dave, actually i did something like that, but was looking if there was any other way..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.