传递Javascript数据属性数组值
我有一个类似于$myArray的php数组传递Javascript数据属性数组值,javascript,php,jquery,arrays,Javascript,Php,Jquery,Arrays,我有一个类似于$myArray的php数组 Array ( [0] => Array ( [Fruit] => Apple [Number] => Array ( [0] => 1 [1] => 2 [2] => 3 )
Array (
[0] => Array (
[Fruit] => Apple
[Number] =>
Array (
[0] => 1
[1] => 2
[2] => 3
)
[supplier] =>
Array (
[0] => Store 1
[1] => Store 2
[2] => Store 3
)
[description] =>
Array (
[0] => SAmple text for apple
[1] => Sample text for apple 2
[2] => Sample text for apple 3
)
[1] => Array (
[Fruit] => Orange
[Number] =>
Array (
[0] => 7
[1] => 8
[2] => 9
)
[supplier] =>
Array (
[0] => Store 4
[1] => Store 5
[2] => Store 6
)
[description] =>
Array (
[0] => SAmple text for orange
[1] => Sample text for orange 2
[2] => Sample text for orange 3
))
我使用for循环和javascript数据属性从这个数组传递值,只需按下按钮打开一个模式
I am looping though all the entries in my array like this
for($index=0; $index < count($myArray); $index++){
<!--some code here -->
<button type="button" class="open-modal btn btn-primary" data-first-fruit="'.$myArray[$index]["description"][0]
这可以正常工作并正确显示apple
但我将处理大量数据并保存如下值
data-first-description="'.$myArray[$index]["description"][0]
data-second-description="'.$myArray[$index]["description"][1]
data-third-description="'.$myArray[$index]["description"][2]
data-first-description="'.$myArray[$index]["description"]
不太理想
每次我像下面这样传递数据
data-first-description="'.$myArray[$index]["description"][0]
data-second-description="'.$myArray[$index]["description"][1]
data-third-description="'.$myArray[$index]["description"][2]
data-first-description="'.$myArray[$index]["description"]
我得到一个数组到字符串的转换错误
是否有一种方法可以将整个[“description”]数据传递给数据属性 这似乎是php(尽管问题没有标记为php)
如果是这样,您可以json\u encode()
将数组传递给数据属性,jQuery data()将把它作为javascript数组读取
使用单引号包装输出,以避免html中的不匹配
data-fruit=\''. json_encode($array) . '\''
当您使用jQuery时,您可以使用
data()
,它不会创建属性,也不会转换为字符串,相反,它将数据直接存储在元素对象上。您可以创建一个数组作为数据标记,如
,然后服务器端或客户端将更容易调用第一秒等。每件事而不是定义数据标记的负载您在这里有多个数组,因此您需要在station前面再创建一个索引$myArray[0][$index][“Fruit”]
我需要更改$myArray的结构吗?我还不能回答这个问题…..我有点不明白您到底想如何使用它,以及为什么会有外部数组。请尝试以下console.log($('[data Fruit']:first')。data('Fruit'))
您可以在浏览器开发工具consoledata first fruit=“”’中看到您正在使用的内容。$myArray[$index][“fruit”][0]按原样工作,我得到了正确的apple。我希望能够在最后去掉[0],只传递所有fruits的值。对……这是一个数组……这就是使用data fruit=”后您要编码的内容“.json_encode($myArray[$index][“Fruit”])。”我得到的是空值