This question already has answers here:
Pass a PHP array to a JavaScript function [duplicate]
                                
                                    (4个答案)
                                
                        
                6年前关闭。
            
        

我有一个数组,像这样:

[['jkjhkfhkjh jkj jkjhk', '54.324705', '-2.749629', '189', 1, 1, 0, 0, 'Test two', '2 ', '10+', 'http://xx.co.uk/xx/?post_type=listings&amp;p=189', '<img width="160" height="85" src="http://www.xx.com/manage/wp-content/uploads/wheelbase.jpg" class="attachment-thumbnail wp-post-image" alt="wheelbase" title="wheelbase">', '189'],['fghfghfgh &nbsp;fghfg hf dfh dfh', '54.323174', '-2.744554', '188', 1, 1, 0, 0, 'Test', '2 ', '10+', 'http://xx/xx/?post_type=listings&amp;p=188', '<img width="160" height="85" src="http://www.xx.com/manage/wp-content/uploads/wheelbase.jpg" class="attachment-thumbnail wp-post-image" alt="wheelbase" title="wheelbase">', '188']];

我使用php获取数据:

echo "[";
  for ($i=0; $i < count($json); $i++) {
    echo "['" . $json[$i]["content"] . "', '". $json[$i]["lat"] . "', '" . $json[$i]["long"] . "', '" . $json[$i]["id"] . "', 1, 1, 0, 0, '" . $json[$i]["title"] . "', '2 ', '10+', '" . $json[$i]["link"] . "', '<img width=\"160\" height=\"85\" src=\"http://www.xx.com/manage/wp-content/uploads/wheelbase.jpg\" class=\"attachment-thumbnail wp-post-image\" alt=\"wheelbase\" title=\"wheelbase\" />', '" . $json[$i]["id"] . "'],";
  }
  echo "]";


(我叫变量$json,忽略了我称它不是json的事实)

因此,我将它们回显到将被隐藏的div中。然后在javascript中选择它,请尝试以下操作:

var locations = $('#listingsarray').html();

似乎可以很好地转换为控制台,但是它以文本而不是数组的形式出现。如何将其转换为数组?

最佳答案

首先,您需要构建数组的有效json表示形式,所使用的技术导致语法无效。这应该为您更好地工作。

$data = array();
for ($i=0; $i < count($json); $i++) {
  $data[] =  array(
                  $json[$i]["content"],
                  $json[$i]["lat"],
                  $json[$i]["long"],
                  $json[$i]["id"],
                  1,
                  1,
                  0,
                  0,
                  $json[$i]["title"],
                  '2',
                  '10+',
                  $json[$i]["link"],
                  '<img width=\"160\" height=\"85\" src=\"http://www.xx.com/manage/wp-content/uploads/wheelbase.jpg\" class=\"attachment-thumbnail wp-post-image\" alt=\"wheelbase\" title=\"wheelbase\" />',
                  $json[$i]["id"]
              );
}
$jsonString = json_encode($data);


然后,如果要将其放入json上下文中,则只需执行此操作

<script>var jsonArray = <?= $jsonString ?>;</script>

07-28 08:27