note 47604 added to ref.array
| From: | OllieMaitland | Date: | Mon, 22 Nov 2004 17:08:36 +0000 |
| Subject: | note 47604 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80882@lists.php.net to get a copy of this message | ||
I have had some trouble finding a function to convert php arrays to JavaScript so I wrote a small
function to deal with multidimensional associative arrays ( i couldn't see how to modify gigi
at orsone dot com one) :
So using gigi at orsone dot com one array it like this:
<?php
function array_php2js($data,$pre) {
foreach($data as $k => $v) {
$rt .=$pre."['".$k."']";
if(is_array($v)) $a[] = "".$rt."=new Array (".count($v).")"; $a =
array_merge($a,array_php2js($v,$rt));
if(is_string($v)) $a[] ="".$rt."=".$v."";
$rt="";
}
return $a;
}
$menuz =
array('Products', 'products.php',
array('Fruit', null,
array('Bananas', 'products.php?cat=bananas'),
array('Apples', 'products.php?cat=apples'),
array('Lemons', 'products.php?cat=lemons')
),
array('Chocolate', 'products.php?cat=chocolate')
);
//the <br /> is just for formatting
print (implode (";\n<br
/>",array_php2js($menuz,'menus')).";\n");
}
?>
This would produce:
menus['0']=Products;
menus['1']=products.php;
menus['2']=new Array (5);
menus['2']['0']=Fruit;
menus['2']['2']=new Array (2);
menus['2']['2']['0']=Bananas;
menus['2']['2']['1']=products.php?cat=bananas;
menus['2']['3']=new Array (2);
menus['2']['3']['0']=Apples;
menus['2']['3']['1']=products.php?cat=apples;
menus['2']['4']=new Array (2);
menus['2']['4']['0']=Lemons;
menus['2']['4']['1']=products.php?cat=lemons;
menus['3']=new Array (2);
menus['3']['0']=Chocolate;
menus['3']['1']=products.php?cat=chocolate;
Hope this helps.
- Ollie Maitland
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47604
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47604&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47604&report=yes
Search -- http://master.php.net/manage/user-notes.php