Jump to content

create a 2D array from 2 single D array


alvaronicardo

Recommended Posts

Hello

can anyone  help me out with code to create a 2 dimension array from 2 single dimension array. for example

$path = array('base', 'category', 'subcategory', 'item');

$location=array('india','USA','UK','RUSSIA',);

now i need to have a @D array which have the following structure

$final[0]=array('base','india');

$final[1]=array('category','USA');

$final[2]=array('subcategory','UK');

$final[3]=array('item','RUSSIA');

Link to comment
Share on other sites

Use a simple "for" loop:

<?php
$path = array('base', 'category', 'subcategory', 'item');
$location=array('india','USA','UK','RUSSIA');
$final = array();
for ($i=0;$i<count($path);++$i) {
   $final[] = array($path[$i],$location[$i]);
}
?>

 

Ken

Link to comment
Share on other sites

Might I suggest an alternative solution that "may" fit your needs better? The values you specified in your example may just be "mock" data that is not representative of the values you are really using. But, at first I thought that the first list of values were "labels" and the second list were "values", but I'm not sure. At the very least you are creating a one-to-one relationship.

 

In that case, a better approach may be to create a single dimension array where one list is used as the keys and the other list is used as the values:

$final = array();
for($i=0, $count=min(count($path), count($location)); $i<$count; ++$i)
{
    $final[$path[$i]] = $location[$i];
}

 

Content of $final

Array
(
    [base] => india
    [category] => USA
    [subcategory] => UK
    [item] => RUSSIA
)

 

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.