2

So I have a multidimensional array in the form (actual array can be much longer 500+ members)

$marr = array(
    array("s_id" => 1, 1.25 , 15),
    array("s_id" => 2, 0.75 , 25),
    array("s_id" => 1, 1.15 , 7) 
); 

I am trying to break it into an array grouped/indexed by the s_id value of the member arrays

$sarr = array(
    1 => array(
        array("s_id" => 1, 1.25 , 15),
        array("s_id" => 1, 1.15 , 7) 
    ),
    2 => array(
        array("s_id" => 2, 0.75 , 25)
    )
);

Is there a built in function in php to do this or some best practice way of doing this?

1
  • why don't you use a database? instead of using multi-dimensional arrays. Commented Mar 3, 2013 at 17:32

1 Answer 1

4

There is no built-in function that can supply this result. Instead, you need to iterate over the array, and check if the key matching the s_id value already exists. If it doesn't create a new array at that key.

$marr = array( array("s_id" => 1, 1.25 , 15),
               array("s_id" => 2, 0.75 , 25),
               array("s_id" => 1, 1.15 , 7) 
             ); 

// Holds the whole output
$output = array();

// Looping over the original array
foreach ($marr as $subarr) {
  // Check if the output array already has the s_id as a key
  if (!isset($output[$subarr['s_id']])) {
    // Initialize it
    $output[$subarr['s_id']] = array();
  }
  // Then append the current sub-array to the s_id array key
  $output[$subarr['s_id']][] = $subarr;
}
// Then call ksort() on the output array
// to sort the s_id keys in ascending order
ksort($output);

http://codepad.viper-7.com/SSBrAl

Prints:

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [s_id] => 1
                    [0] => 1.25
                    [1] => 15
                )

            [1] => Array
                (
                    [s_id] => 1
                    [0] => 1.15
                    [1] => 7
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [s_id] => 2
                    [0] => 0.75
                    [1] => 25
                )

        )

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

1 Comment

if (!isset($output[$subarr['s_id']])) { $output[$subarr['s_id']] = array(); } is entirely unneeded.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.