如何将PHP数组转换成这样的格式
Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
[5] => AP1W3242
[6] => AP7X1234
[7] => AS1234
[8] => MH9Z2324
[9] => MX1234
[10] => TN1A3242
[11] => ZZ1234
)
到下面格式的Javascript数组?
var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi",
"Adena",
"Adrian",
"Akron",
"Albany"
];
我使用了一个伪php数组
<?php
// instead to create your array like this
$php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];
// do it like this (a simple variable but with separator)
$php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',');
</script>
如果你的数组是未知的(已经创建)
<?php
$php_array = file('my_file.txt');
$php_fake_array = "";
// transform your array with concatenate like this
foreach ($php_array as $cell){
// since this array is unknown, use clever separator
$php_fake_array .= $cell.",,,,,";
}
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');
</script>
我也遇到了同样的问题,我就是这样做的。
/*PHP FILE*/
<?php
$data = file_get_contents('http://yourrssdomain.com/rss');
$data = simplexml_load_string($data);
$articles = array();
foreach($data->channel->item as $item){
$articles[] = array(
'title' => (string)$item->title,
'description' => (string)$item ->description,
'link' => (string)$item ->link,
'guid' => (string)$item ->guid,
'pubdate' => (string)$item ->pubDate,
'category' => (string)$item ->category,
);
}
// IF YOU PRINT_R THE ARTICLES ARRAY YOU WILL GET THE SAME KIND OF ARRAY THAT YOU ARE GETTING SO I CREATE AN OUTPUT STING AND WITH A FOR LOOP I ADD SOME CHARACTERS TO SPLIT LATER WITH JAVASCRIPT
$output="";
for($i = 0; $i < sizeof($articles); $i++){
//# Items
//| Attributes
if($i != 0) $output.="#"; /// IF NOT THE FIRST
// IF NOT THE FIRST ITEM ADD '#' TO SEPARATE EACH ITEM AND THEN '|' TO SEPARATE EACH ATTRIBUTE OF THE ITEM
$output.=$articles[$i]['title']."|";
$output.=$articles[$i]['description']."|";
$output.=$articles[$i]['link']."|";
$output.=$articles[$i]['guid']."|";
$output.=$articles[$i]['pubdate']."|";
$output.=$articles[$i]['category'];
}
echo $output;
?>
/* php file */
/*AJAX COMUNICATION*/
$(document).ready(function(e) {
/*AJAX COMUNICATION*/
var prodlist= [];
var attrlist= [];
$.ajax({
type: "get",
url: "php/fromupnorthrss.php",
data: {feeding: "feedstest"},
}).done(function(data) {
prodlist= data.split('#');
for(var i = 0; i < prodlist.length; i++){
attrlist= prodlist[i].split('|');
alert(attrlist[0]); /// NOW I CAN REACH EACH ELEMENT HOW I WANT TO.
}
});
});
我希望这能有所帮助。