简体   繁体   English

将javascript字符串转换为php数组

[英]Convert javascript string to php array

I'm scraping a website using php to get some data. 我正在使用php抓取一个网站来获取一些数据。 The data I get is a valid javascript array. 我得到的数据是一个有效的javascript数组。

          "['v42, 2015', 23428, 30243, 76993]
                ,
          ['v43, 2015', 24060, 30401, 73412]
                ,
          ['v44, 2015', 22855, 29720, 71573]
                ,
          ['v45, 2015', 24455, 30757, 78991]
                ,
          ['v46, 2015', 24275, 30398, 84424]"

I now have this string in php, but how can I convert it to a php array? 我现在在php中有这个字符串,但是如何将其转换为php数组呢?

$string = "['v42, 2015', 23428, 30243, 76993]
                ,
          ['v43, 2015', 24060, 30401, 73412]
                ,
          ['v44, 2015', 22855, 29720, 71573]
                ,
          ['v45, 2015', 24455, 30757, 78991]
                ,
          ['v46, 2015', 24275, 30398, 84424]";

It is a valid js array if you add the proper start & end square brackets delimiter. 如果添加正确的开始和结束方括号分隔符,它是一个有效的js数组。 Furthermore, to comply with the php json parser requirements, the string delimiters must be double-quoted instead of single-quoted, so a quick replacement must be done. 此外,为了符合php json解析器要求,字符串分隔符必须是双引号而不是单引号,因此必须快速替换。

You then can decode it like so : 然后你可以像这样解码它:

$ary = json_decode('['.str_replace("'",'"',$string).']', true);

The single quotes may be valid in JS, but JSON sometimes have a problem with it. 单引号可能在JS中有效,但JSON有时会出现问题。 You can try it here: JSONLint 你可以在这里试试: JSONLint

To get a valid JSON, just replace the single quotes ' with double quotes " , to get an array with arrays you have to surround your string with brackets [] . 要获得有效的JSON,只需将单引号'替换为'双引号" ,以获得包含数组的数组,您必须用括号[]包围字符串。

Try this example code: 试试这个示例代码:

$string = "['v42, 2015', 23428, 30243, 76993]
                ,
          ['v43, 2015', 24060, 30401, 73412]
                ,
          ['v44, 2015', 22855, 29720, 71573]
                ,
          ['v45, 2015', 24455, 30757, 78991]
                ,
          ['v46, 2015', 24275, 30398, 84424]";

$string = str_replace( "'" , '"', $string );
$string = '['.$string.']';

echo "<pre>";
var_dump( json_decode( $string ) );

You can try replacing the [ ] with '' and then breaking the string. 你可以尝试用''替换[ ] ,然后打破字符串。

$string = str_replace(']', '', str_replace('[', '',$string));
$array = explode(',', $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM