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
https://forums.phpfreaks.com/topic/215297-create-a-2d-array-from-2-single-d-array/
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

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
)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.