Jump to content

[SOLVED] How to call a column instead of row in a multidimensional array


cmor

Recommended Posts

Very simple question but I'm having trouble finding an answer by searching the forum.

 

I have a 2-d array.  I want to pass columns from the 2-d array to a file that will graph the columns.

 

Let's say its called my2darray

 

I can pass a row with something like my2darray[4]

 

But I can't pass a specific column with my2darray[][4]

 

Any help with the syntax or a link to the solution would be helpful.  Do I have to use a loop to call a whole column?

Thanks for the help. 

Link to comment
Share on other sites

try

<?php
function cols2rows(&$array)
{
    $newarray = array();
    foreach ($array as $ar)
    {
        $k = count($ar);
        for ($i=0; $i<$k; $i++)
        {
            $newarray[$i][] = $ar[$i];
        }
    }
    return $newarray;
}


$my2darray = array (
            array ('a', 1,2,3,4),
            array ('b', 2,3,4,5),
            array ('c', 3,4,5,6)
        );

$new2d = cols2rows($my2darray);
?>

 

Now pass $new2d[4] to the graph.

Link to comment
Share on other sites

That, or loop through the array each time gathering the contents of the Nth element.

$data = array();
foreach ($my2darray as $ar)
{
     $data[] = $ar[4];
}

As you said you wanted to pass columns (plural) to the graph, I thought you may as well do them all in one operation

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.