我想要组合以下数组:
<?php
$data_a = '{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12}';
?>
<script>
array1 = [<?=$data_a?>];
var data_b = '{"a":1,"b":2,"c":3}';
array2 = JSON.parse(data_b);
</script>
我已经尝试过并没有成功将它们组合成如下:
combined = array2.concat(array1);
我希望组合数组返回
[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12}]
任何人的帮助将不胜感激!
答案 0 :(得分:1)
array1
是array Object
,array2
是一个对象,在您的示例中,您希望array2进入array1,请参阅:
[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12}]
尝试:
array1.push(array2);
注意,结果返回:
[{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12},{"a":1,"b":2,"c":3}]
如果需要{"a":1,"b":2,"c":3}
在&#34;第一个索引&#34;使用Array.unshit
,尝试:
array1.unshift(array2);
提示,声明变量:
<script>
var array1 = [<?=$data_a?>];
var data_b = '{"a":1,"b":2,"c":3}';
var array2 = JSON.parse(data_b);
console.log(array1.push(array2));
</script>
答案 1 :(得分:0)
答案 2 :(得分:0)
你需要尝试这样
<?php
$data_a = '{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12}';
?>
<script>
var array1 = '<?=$data_a?>'; //removed [] and added var
var data_b = '{"a":1,"b":2,"c":3}'; // removed JSON.parse
combined = data_b.concat(array1); // concated data_b with array1
</script>
答案 3 :(得分:-2)
实际上非常直接。
<?php
$data_a = '{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9},{"a":10,"b":11,"c":12}';
?>
<script>
var data_b = '[<?php echo $data_a;?>,{"a":1,"b":2,"c":3}]';
combinedArr = JSON.parse(data_b);
// combinedArr is the combined array.
</script>
但它的缺点是你需要确保你的PHP数据不是空的,否则你会得到解析错误。