将PHP数组转换为Javascript数组

时间:2015-05-31 20:18:02

标签: javascript php

在网上寻找答案后,我找不到解决问题的方法: 我不断得到一个长度为1的数组。

我的代码如下所示:

<?php
    echo "var PlayerPokemon1 = ".$jsPoke1.";\n";
?>

返回

PlayerPokemon1 = [{"Number":"9","0":"9","Name":"Rock Slide","1":"Blastoise","Type1":"Water","2":"Water","Type2":"","3":"","HP":"362","4":"362","Attack":"295","5":"295"}]

这只是一个巨大的对象,我想要实现的就是

  

PlayerPokemon1 = [“9”,“9”,“Rock Slide”,“Blastoise”,“Water”]

等等......

我尝试过其他方法

$numArray = count($jsPoke1);
for ($i=0; i<$numArray; i++)
{
    echo "PlayerPokemon1[$i] = ".jsPoke1[$i].";\n";
}

但无济于事。

编辑:

print_r ($poke1);

gives this:

Array ( [0] => Array ( [Number] => 9 [0] => 9 [Name] => Rock Slide [1] => Blastoise [Type1] => Water [2] => Water [Type2] => [3] => [HP] => 362 [4] => 362 [Attack] => 295 [5] => 295 [Defense] => 339 [6] => 339 [Speed] => 280 [7] => 280 [Move1] => Aqua Tail [8] => Aqua Tail [Move2] => Ice Beam [9] => Ice Beam [Move3] => Dark Pulse [10] => Dark Pulse [Move4] => Rock Slide [11] => Rock Slide [12] => Aqua Tail [Type] => Rock [13] => Water [Power] => 75 [14] => 90 [15] => Ice Beam [16] => Ice [17] => 90 [18] => Dark Pulse [19] => Dark [20] => 80 [21] => Rock Slide [22] => Rock [23] => 75 ) )

并且

$jsPoke1 = json_encode($Poke1);
print_r ($jsPoke1);

[{"Number":"9","0":"9","Name":"Rock Slide","1":"Blastoise","Type1":"Water","2":"Water","Type2":"","3":"","HP":"362","4":"362","Attack":"295","5":"295","Defense":"339","6":"339","Speed":"280","7":"280","Move1":"Aqua Tail","8":"Aqua Tail","Move2":"Ice Beam","9":"Ice Beam","Move3":"Dark Pulse","10":"Dark Pulse","Move4":"Rock Slide","11":"Rock Slide","12":"Aqua Tail","Type":"Rock","13":"Water","Power":"75","14":"90","15":"Ice Beam","16":"Ice","17":"90","18":"Dark Pulse ","19":"Dark","20":"80","21":"Rock Slide","22":"Rock","23":"75"}]

最终,我想要的是一个Javascript数组,其值以数字形式索引,如[“9”,“9”,“Blastoise”]

1 个答案:

答案 0 :(得分:0)

从你的问题来看,目前还不清楚你想要Blastoise或PlayerPokemon1中的所有口袋妖怪的天气,但我会尝试给出一个可行的方法。 You can try this code here

如果您的$jsPoke1数组看起来像

$jsPoke1 = [
  [//Blastoise
    'Number' => 9,
    0 => 9,
    1 => 'Blastoise',
    'Name' => 'Rock Slike',
    ],
  [//Totodile
    'Number' => 5,
    0 => 2,
    1 => 'Totodile',
    'Name' => 'Water Gun',
    ]
  ];

你可以做到

$formattedPokemons = array_map(function($pokemon){
  return array_values($pokemon);
}, $jsPoke1);

如果您想要PlayerPokemon1

中的所有口袋妖怪,请执行以下操作
echo "var PlayerPokemon1 = ".json_encode($formattedPokemons);

或者如果你只想要Blastoise那么另外一件事

echo "var PlayerPokemon1 = ".json_encode($formattedPokemons[0]);