0

I have the array about:

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

    [product] => Array
        (
            [0] => t-shirt
            [1] => earing
            [2] => clock
        )

    [price] => Array
        (
            [0] => 100.00
            [1] => 32.00
            [2] => 898.00
        )

)

I want to do this:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => t-shirt
            [2] => 100.00
        )

    [1] => Array
        (
            [0] => 2
            [1] => earing
            [2] => 32.00
        )

    [2] => Array
        (
            [0] => 3
            [1] => clock
            [2] => 898.00
        )

)
2
  • 1
    I'd personally use a foreach loop, what have you tried so far? Commented Feb 24, 2014 at 17:55
  • 1
    If I were you, I would actually map that into an array of objects or an array of associative arrays. The way you propose would cause you to lose your keys! Commented Feb 24, 2014 at 17:57

2 Answers 2

1

You can try with:

$input  = array( /* your input array */ );
$output = array();

foreach ($input as $data) {
  for ($i = 0; $i < count($data); $i++) {
    if (!isset($output[$i])) {
      $output[$i] = array();
    }
    $output[$i][] = $data[$i];
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

if (!isset($output[$i])) { $output[$i] = array(); } can be completely omitted because you are pushing with square brace syntax.
0

Well or like this.

  $test = array(
          'id' => array(
              1,2,3
          ),
         'product' => array(
                'tshirt', 'ewew', 'shorts'
          ),
         'price' => array(
             '10.00', '20.00', '30.00'
         )

        );

        $newarray = array();
        foreach($test['id'] as $k => $v){
            $newarray[$k] = array(
                $v, $test['product'][$k], $test['price'][$k]
            );
        }
        echo '<pre>';
        print_r($newarray);

Example live

1 Comment

Thanks for help, I try your exemple and working well, Now I'm studing the code to understand it step-by-step.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.