Transposing a PHP associative arrayMySQLi_Recordset: blending SPL and Statement/Query resultsEfficiently accessing the databaseSimulating Natural Sorting in MySQL with PHPUsing 2D arrays to make more efficient sequential storageMapping arbitrary Int values to a linear index spaceEmail Template Parser PHP ClassPopulating an array from a databaseAssigning entire column of data to specific column of an array in VBAReform PHP associative arraySearching for column-indices of a multi-dimensional array that match multiple conditions (one condition per row)

Can a German sentence have two subjects?

Why is an old chain unsafe?

How to report a triplet of septets in NMR tabulation?

Patience, young "Padovan"

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

Why is "Reports" in sentence down without "The"

Is it possible to do 50 km distance without any previous training?

Are white and non-white police officers equally likely to kill black suspects?

Why is the design of haulage companies so “special”?

Banach space and Hilbert space topology

Is there really no realistic way for a skeleton monster to move around without magic?

Why is this code 6.5x slower with optimizations enabled?

declaring a variable twice in IIFE

least quadratic residue under GRH: an EXPLICIT bound

Concept of linear mappings are confusing me

XeLaTeX and pdfLaTeX ignore hyphenation

How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Why Is Death Allowed In the Matrix?

How do I create uniquely male characters?

I see my dog run

Is there a familial term for apples and pears?

What is the white spray-pattern residue inside these Falcon Heavy nozzles?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?



Transposing a PHP associative array


MySQLi_Recordset: blending SPL and Statement/Query resultsEfficiently accessing the databaseSimulating Natural Sorting in MySQL with PHPUsing 2D arrays to make more efficient sequential storageMapping arbitrary Int values to a linear index spaceEmail Template Parser PHP ClassPopulating an array from a databaseAssigning entire column of data to specific column of an array in VBAReform PHP associative arraySearching for column-indices of a multi-dimensional array that match multiple conditions (one condition per row)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.



<?php

$arr = [
'name' => ['a', 'b', 'c'],
'age' => [ 2 , 1 , 3 ]
];

$result = [];
$keys = array_keys($arr);
foreach($arr[$keys[0]] as $index => $temp)
$data = [];
foreach($keys as $i => $key)
$data[$key] = $arr[$key][$index];

$result[] = $data;


print_r($result);


Which gives:



$result = [
['name' => 'a', 'age' => 2],
['name' => 'b', 'age' => 1],
['name' => 'c', 'age' => 3],
];









share|improve this question











$endgroup$


















    4












    $begingroup$


    The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.



    <?php

    $arr = [
    'name' => ['a', 'b', 'c'],
    'age' => [ 2 , 1 , 3 ]
    ];

    $result = [];
    $keys = array_keys($arr);
    foreach($arr[$keys[0]] as $index => $temp)
    $data = [];
    foreach($keys as $i => $key)
    $data[$key] = $arr[$key][$index];

    $result[] = $data;


    print_r($result);


    Which gives:



    $result = [
    ['name' => 'a', 'age' => 2],
    ['name' => 'b', 'age' => 1],
    ['name' => 'c', 'age' => 3],
    ];









    share|improve this question











    $endgroup$














      4












      4








      4





      $begingroup$


      The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.



      <?php

      $arr = [
      'name' => ['a', 'b', 'c'],
      'age' => [ 2 , 1 , 3 ]
      ];

      $result = [];
      $keys = array_keys($arr);
      foreach($arr[$keys[0]] as $index => $temp)
      $data = [];
      foreach($keys as $i => $key)
      $data[$key] = $arr[$key][$index];

      $result[] = $data;


      print_r($result);


      Which gives:



      $result = [
      ['name' => 'a', 'age' => 2],
      ['name' => 'b', 'age' => 1],
      ['name' => 'c', 'age' => 3],
      ];









      share|improve this question











      $endgroup$




      The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.



      <?php

      $arr = [
      'name' => ['a', 'b', 'c'],
      'age' => [ 2 , 1 , 3 ]
      ];

      $result = [];
      $keys = array_keys($arr);
      foreach($arr[$keys[0]] as $index => $temp)
      $data = [];
      foreach($keys as $i => $key)
      $data[$key] = $arr[$key][$index];

      $result[] = $data;


      print_r($result);


      Which gives:



      $result = [
      ['name' => 'a', 'age' => 2],
      ['name' => 'b', 'age' => 1],
      ['name' => 'c', 'age' => 3],
      ];






      php array






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 24 '16 at 19:11









      200_success

      131k17157422




      131k17157422










      asked Oct 24 '16 at 17:09









      Sam YeSam Ye

      234




      234




















          5 Answers
          5






          active

          oldest

          votes


















          1












          $begingroup$

          Like you, I don't see a better way than basing the method on evaluating array_keys($arr), then iterate it to build each new member.



          But there are two possible slight improvement in how to it:



          $arr = [
          'name' => ['a', 'b', 'c'],
          'age' => [ 2 , 1 , 3 ]
          ];

          $result = [];
          $keys = array_keys($arr);
          for ($row = 0, $rows = count(reset($arr)); $row < $rows; $row++)
          foreach ($keys as $key)
          $result[$row][$key] = $arr[$key][$row];



          echo '<pre>' . print_r($result, true) . '</pre>';


          The first (and somewhat obvious) improvement is: not to use intermediary variable data.



          I'm not really sure of the second one: I tend to think that the for() loop will be faster, because it accesses $arr only once (count(reset($arr))), while the foreach() loop have to extract data from $arr on each step.






          share|improve this answer









          $endgroup$




















            1












            $begingroup$

            There isn't really any great performance improvement to be made here in my opinion. You original structure is going to require nested loop approach to generate your desired structure regardless.



            My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).






            share|improve this answer









            $endgroup$




















              1












              $begingroup$

              If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one loop, then array_column() and array_combine() are useful:



              Code: (Demo)



              $arr = [
              'name' => ['a', 'b', 'c', 'd'],
              'age' => [ 2 , 1 , 3 , 4 ],
              'shoe' => [11 , 9 , 8 , 10 ],
              'kids' => [ 1 , 0 , 2 , 3 ]
              ];
              $keys = array_keys($arr);
              foreach ($arr[$keys[0]] as $k => $v) // only iterate first "row"
              $result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"

              var_export($result);


              Output:



              array (
              0 =>
              array (
              'name' => 'a',
              'age' => 2,
              'shoe' => 11,
              'kids' => 1,
              ),
              1 =>
              array (
              'name' => 'b',
              'age' => 1,
              'shoe' => 9,
              'kids' => 0,
              ),
              2 =>
              array (
              'name' => 'c',
              'age' => 3,
              'shoe' => 8,
              'kids' => 2,
              ),
              3 =>
              array (
              'name' => 'd',
              'age' => 4,
              'shoe' => 10,
              'kids' => 3,
              ),
              )





              share|improve this answer











              $endgroup$




















                0












                $begingroup$

                You can use normal for loop like this :



                <?php

                $arr = [
                'name' => ['a', 'b', 'c'],
                'age' => [ 2 , 1 , 3 ]
                ];

                $new_array=array();
                $acount=count($arr['name']);

                for($i=0;$i<$acount;$i++)

                $new_array[$i]['name']=$arr['name'][$i];

                $new_array[$i]['age']=$arr['age'][$i];




                ?>





                share|improve this answer









                $endgroup$








                • 1




                  $begingroup$
                  You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                  $endgroup$
                  – mdfst13
                  Oct 25 '16 at 15:07


















                0












                $begingroup$

                If you have 2 attributes: name, age and unique name, may be helpful I think)



                $userData = array_combine($arr['name'], $arr['age']);

                foreach($userData as $name => $age)





                share|improve this answer









                $endgroup$













                  Your Answer





                  StackExchange.ifUsing("editor", function ()
                  return StackExchange.using("mathjaxEditing", function ()
                  StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
                  StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                  );
                  );
                  , "mathjax-editing");

                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "196"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f145117%2ftransposing-a-php-associative-array%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  1












                  $begingroup$

                  Like you, I don't see a better way than basing the method on evaluating array_keys($arr), then iterate it to build each new member.



                  But there are two possible slight improvement in how to it:



                  $arr = [
                  'name' => ['a', 'b', 'c'],
                  'age' => [ 2 , 1 , 3 ]
                  ];

                  $result = [];
                  $keys = array_keys($arr);
                  for ($row = 0, $rows = count(reset($arr)); $row < $rows; $row++)
                  foreach ($keys as $key)
                  $result[$row][$key] = $arr[$key][$row];



                  echo '<pre>' . print_r($result, true) . '</pre>';


                  The first (and somewhat obvious) improvement is: not to use intermediary variable data.



                  I'm not really sure of the second one: I tend to think that the for() loop will be faster, because it accesses $arr only once (count(reset($arr))), while the foreach() loop have to extract data from $arr on each step.






                  share|improve this answer









                  $endgroup$

















                    1












                    $begingroup$

                    Like you, I don't see a better way than basing the method on evaluating array_keys($arr), then iterate it to build each new member.



                    But there are two possible slight improvement in how to it:



                    $arr = [
                    'name' => ['a', 'b', 'c'],
                    'age' => [ 2 , 1 , 3 ]
                    ];

                    $result = [];
                    $keys = array_keys($arr);
                    for ($row = 0, $rows = count(reset($arr)); $row < $rows; $row++)
                    foreach ($keys as $key)
                    $result[$row][$key] = $arr[$key][$row];



                    echo '<pre>' . print_r($result, true) . '</pre>';


                    The first (and somewhat obvious) improvement is: not to use intermediary variable data.



                    I'm not really sure of the second one: I tend to think that the for() loop will be faster, because it accesses $arr only once (count(reset($arr))), while the foreach() loop have to extract data from $arr on each step.






                    share|improve this answer









                    $endgroup$















                      1












                      1








                      1





                      $begingroup$

                      Like you, I don't see a better way than basing the method on evaluating array_keys($arr), then iterate it to build each new member.



                      But there are two possible slight improvement in how to it:



                      $arr = [
                      'name' => ['a', 'b', 'c'],
                      'age' => [ 2 , 1 , 3 ]
                      ];

                      $result = [];
                      $keys = array_keys($arr);
                      for ($row = 0, $rows = count(reset($arr)); $row < $rows; $row++)
                      foreach ($keys as $key)
                      $result[$row][$key] = $arr[$key][$row];



                      echo '<pre>' . print_r($result, true) . '</pre>';


                      The first (and somewhat obvious) improvement is: not to use intermediary variable data.



                      I'm not really sure of the second one: I tend to think that the for() loop will be faster, because it accesses $arr only once (count(reset($arr))), while the foreach() loop have to extract data from $arr on each step.






                      share|improve this answer









                      $endgroup$



                      Like you, I don't see a better way than basing the method on evaluating array_keys($arr), then iterate it to build each new member.



                      But there are two possible slight improvement in how to it:



                      $arr = [
                      'name' => ['a', 'b', 'c'],
                      'age' => [ 2 , 1 , 3 ]
                      ];

                      $result = [];
                      $keys = array_keys($arr);
                      for ($row = 0, $rows = count(reset($arr)); $row < $rows; $row++)
                      foreach ($keys as $key)
                      $result[$row][$key] = $arr[$key][$row];



                      echo '<pre>' . print_r($result, true) . '</pre>';


                      The first (and somewhat obvious) improvement is: not to use intermediary variable data.



                      I'm not really sure of the second one: I tend to think that the for() loop will be faster, because it accesses $arr only once (count(reset($arr))), while the foreach() loop have to extract data from $arr on each step.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 26 '16 at 13:33









                      cFreedcFreed

                      2,4831020




                      2,4831020























                          1












                          $begingroup$

                          There isn't really any great performance improvement to be made here in my opinion. You original structure is going to require nested loop approach to generate your desired structure regardless.



                          My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).






                          share|improve this answer









                          $endgroup$

















                            1












                            $begingroup$

                            There isn't really any great performance improvement to be made here in my opinion. You original structure is going to require nested loop approach to generate your desired structure regardless.



                            My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).






                            share|improve this answer









                            $endgroup$















                              1












                              1








                              1





                              $begingroup$

                              There isn't really any great performance improvement to be made here in my opinion. You original structure is going to require nested loop approach to generate your desired structure regardless.



                              My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).






                              share|improve this answer









                              $endgroup$



                              There isn't really any great performance improvement to be made here in my opinion. You original structure is going to require nested loop approach to generate your desired structure regardless.



                              My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 24 '16 at 18:37









                              Mike BrantMike Brant

                              8,878722




                              8,878722





















                                  1












                                  $begingroup$

                                  If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one loop, then array_column() and array_combine() are useful:



                                  Code: (Demo)



                                  $arr = [
                                  'name' => ['a', 'b', 'c', 'd'],
                                  'age' => [ 2 , 1 , 3 , 4 ],
                                  'shoe' => [11 , 9 , 8 , 10 ],
                                  'kids' => [ 1 , 0 , 2 , 3 ]
                                  ];
                                  $keys = array_keys($arr);
                                  foreach ($arr[$keys[0]] as $k => $v) // only iterate first "row"
                                  $result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"

                                  var_export($result);


                                  Output:



                                  array (
                                  0 =>
                                  array (
                                  'name' => 'a',
                                  'age' => 2,
                                  'shoe' => 11,
                                  'kids' => 1,
                                  ),
                                  1 =>
                                  array (
                                  'name' => 'b',
                                  'age' => 1,
                                  'shoe' => 9,
                                  'kids' => 0,
                                  ),
                                  2 =>
                                  array (
                                  'name' => 'c',
                                  'age' => 3,
                                  'shoe' => 8,
                                  'kids' => 2,
                                  ),
                                  3 =>
                                  array (
                                  'name' => 'd',
                                  'age' => 4,
                                  'shoe' => 10,
                                  'kids' => 3,
                                  ),
                                  )





                                  share|improve this answer











                                  $endgroup$

















                                    1












                                    $begingroup$

                                    If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one loop, then array_column() and array_combine() are useful:



                                    Code: (Demo)



                                    $arr = [
                                    'name' => ['a', 'b', 'c', 'd'],
                                    'age' => [ 2 , 1 , 3 , 4 ],
                                    'shoe' => [11 , 9 , 8 , 10 ],
                                    'kids' => [ 1 , 0 , 2 , 3 ]
                                    ];
                                    $keys = array_keys($arr);
                                    foreach ($arr[$keys[0]] as $k => $v) // only iterate first "row"
                                    $result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"

                                    var_export($result);


                                    Output:



                                    array (
                                    0 =>
                                    array (
                                    'name' => 'a',
                                    'age' => 2,
                                    'shoe' => 11,
                                    'kids' => 1,
                                    ),
                                    1 =>
                                    array (
                                    'name' => 'b',
                                    'age' => 1,
                                    'shoe' => 9,
                                    'kids' => 0,
                                    ),
                                    2 =>
                                    array (
                                    'name' => 'c',
                                    'age' => 3,
                                    'shoe' => 8,
                                    'kids' => 2,
                                    ),
                                    3 =>
                                    array (
                                    'name' => 'd',
                                    'age' => 4,
                                    'shoe' => 10,
                                    'kids' => 3,
                                    ),
                                    )





                                    share|improve this answer











                                    $endgroup$















                                      1












                                      1








                                      1





                                      $begingroup$

                                      If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one loop, then array_column() and array_combine() are useful:



                                      Code: (Demo)



                                      $arr = [
                                      'name' => ['a', 'b', 'c', 'd'],
                                      'age' => [ 2 , 1 , 3 , 4 ],
                                      'shoe' => [11 , 9 , 8 , 10 ],
                                      'kids' => [ 1 , 0 , 2 , 3 ]
                                      ];
                                      $keys = array_keys($arr);
                                      foreach ($arr[$keys[0]] as $k => $v) // only iterate first "row"
                                      $result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"

                                      var_export($result);


                                      Output:



                                      array (
                                      0 =>
                                      array (
                                      'name' => 'a',
                                      'age' => 2,
                                      'shoe' => 11,
                                      'kids' => 1,
                                      ),
                                      1 =>
                                      array (
                                      'name' => 'b',
                                      'age' => 1,
                                      'shoe' => 9,
                                      'kids' => 0,
                                      ),
                                      2 =>
                                      array (
                                      'name' => 'c',
                                      'age' => 3,
                                      'shoe' => 8,
                                      'kids' => 2,
                                      ),
                                      3 =>
                                      array (
                                      'name' => 'd',
                                      'age' => 4,
                                      'shoe' => 10,
                                      'kids' => 3,
                                      ),
                                      )





                                      share|improve this answer











                                      $endgroup$



                                      If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one loop, then array_column() and array_combine() are useful:



                                      Code: (Demo)



                                      $arr = [
                                      'name' => ['a', 'b', 'c', 'd'],
                                      'age' => [ 2 , 1 , 3 , 4 ],
                                      'shoe' => [11 , 9 , 8 , 10 ],
                                      'kids' => [ 1 , 0 , 2 , 3 ]
                                      ];
                                      $keys = array_keys($arr);
                                      foreach ($arr[$keys[0]] as $k => $v) // only iterate first "row"
                                      $result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"

                                      var_export($result);


                                      Output:



                                      array (
                                      0 =>
                                      array (
                                      'name' => 'a',
                                      'age' => 2,
                                      'shoe' => 11,
                                      'kids' => 1,
                                      ),
                                      1 =>
                                      array (
                                      'name' => 'b',
                                      'age' => 1,
                                      'shoe' => 9,
                                      'kids' => 0,
                                      ),
                                      2 =>
                                      array (
                                      'name' => 'c',
                                      'age' => 3,
                                      'shoe' => 8,
                                      'kids' => 2,
                                      ),
                                      3 =>
                                      array (
                                      'name' => 'd',
                                      'age' => 4,
                                      'shoe' => 10,
                                      'kids' => 3,
                                      ),
                                      )






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 15 mins ago

























                                      answered Jun 23 '17 at 14:33









                                      mickmackusamickmackusa

                                      2,079219




                                      2,079219





















                                          0












                                          $begingroup$

                                          You can use normal for loop like this :



                                          <?php

                                          $arr = [
                                          'name' => ['a', 'b', 'c'],
                                          'age' => [ 2 , 1 , 3 ]
                                          ];

                                          $new_array=array();
                                          $acount=count($arr['name']);

                                          for($i=0;$i<$acount;$i++)

                                          $new_array[$i]['name']=$arr['name'][$i];

                                          $new_array[$i]['age']=$arr['age'][$i];




                                          ?>





                                          share|improve this answer









                                          $endgroup$








                                          • 1




                                            $begingroup$
                                            You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                            $endgroup$
                                            – mdfst13
                                            Oct 25 '16 at 15:07















                                          0












                                          $begingroup$

                                          You can use normal for loop like this :



                                          <?php

                                          $arr = [
                                          'name' => ['a', 'b', 'c'],
                                          'age' => [ 2 , 1 , 3 ]
                                          ];

                                          $new_array=array();
                                          $acount=count($arr['name']);

                                          for($i=0;$i<$acount;$i++)

                                          $new_array[$i]['name']=$arr['name'][$i];

                                          $new_array[$i]['age']=$arr['age'][$i];




                                          ?>





                                          share|improve this answer









                                          $endgroup$








                                          • 1




                                            $begingroup$
                                            You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                            $endgroup$
                                            – mdfst13
                                            Oct 25 '16 at 15:07













                                          0












                                          0








                                          0





                                          $begingroup$

                                          You can use normal for loop like this :



                                          <?php

                                          $arr = [
                                          'name' => ['a', 'b', 'c'],
                                          'age' => [ 2 , 1 , 3 ]
                                          ];

                                          $new_array=array();
                                          $acount=count($arr['name']);

                                          for($i=0;$i<$acount;$i++)

                                          $new_array[$i]['name']=$arr['name'][$i];

                                          $new_array[$i]['age']=$arr['age'][$i];




                                          ?>





                                          share|improve this answer









                                          $endgroup$



                                          You can use normal for loop like this :



                                          <?php

                                          $arr = [
                                          'name' => ['a', 'b', 'c'],
                                          'age' => [ 2 , 1 , 3 ]
                                          ];

                                          $new_array=array();
                                          $acount=count($arr['name']);

                                          for($i=0;$i<$acount;$i++)

                                          $new_array[$i]['name']=$arr['name'][$i];

                                          $new_array[$i]['age']=$arr['age'][$i];




                                          ?>






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Oct 25 '16 at 14:49









                                          mohademohade

                                          1012




                                          1012







                                          • 1




                                            $begingroup$
                                            You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                            $endgroup$
                                            – mdfst13
                                            Oct 25 '16 at 15:07












                                          • 1




                                            $begingroup$
                                            You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                            $endgroup$
                                            – mdfst13
                                            Oct 25 '16 at 15:07







                                          1




                                          1




                                          $begingroup$
                                          You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                          $endgroup$
                                          – mdfst13
                                          Oct 25 '16 at 15:07




                                          $begingroup$
                                          You certainly could do that. Why would you want to do so? In particular, note that the original code handled arbitrary array keys. You're manually specifying each key, so you'd have to rewrite the code for each task. So you should show some advantage to this code that outweighs the flexibility of the original code. In general, remember that we are Code Review. Why we make decisions in our code is as important as the code itself.
                                          $endgroup$
                                          – mdfst13
                                          Oct 25 '16 at 15:07











                                          0












                                          $begingroup$

                                          If you have 2 attributes: name, age and unique name, may be helpful I think)



                                          $userData = array_combine($arr['name'], $arr['age']);

                                          foreach($userData as $name => $age)





                                          share|improve this answer









                                          $endgroup$

















                                            0












                                            $begingroup$

                                            If you have 2 attributes: name, age and unique name, may be helpful I think)



                                            $userData = array_combine($arr['name'], $arr['age']);

                                            foreach($userData as $name => $age)





                                            share|improve this answer









                                            $endgroup$















                                              0












                                              0








                                              0





                                              $begingroup$

                                              If you have 2 attributes: name, age and unique name, may be helpful I think)



                                              $userData = array_combine($arr['name'], $arr['age']);

                                              foreach($userData as $name => $age)





                                              share|improve this answer









                                              $endgroup$



                                              If you have 2 attributes: name, age and unique name, may be helpful I think)



                                              $userData = array_combine($arr['name'], $arr['age']);

                                              foreach($userData as $name => $age)






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 25 '16 at 20:02









                                              dns_projectdns_project

                                              213




                                              213



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Code Review Stack Exchange!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  Use MathJax to format equations. MathJax reference.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f145117%2ftransposing-a-php-associative-array%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

                                                  Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

                                                  चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि