转换"爆炸"的输出从字符串到数组

时间:2017-12-20 18:18:20

标签: php multidimensional-array explode

如何转换" explode"的字符串输出?进入阵列?

鉴于此字符串:

$long_string = '("name" => "Able","company" => "Tesla","haircolor" => 
"brown","name" => "Aaaa","home" => "Kansas","shoe" => 12,)<>( "name" => 
"Bob","company" => "Target","haircolor" => "red","name" => "Bbbb","home" => 
"Ohio","shoe" => 11.5)' ;

爆炸将产生一个包含2个字符串的数组。

$multi_strings =  explode("<>",$long_string); 

$ multi_strings是一个包含2个字符串的数组:

array(2) {
  [0]=> string(112) "("name" => "Able","company" => "Tesla","haircolor" => 
  "brown","name" => "Aaaa","home" => "Kansas","shoe" => 12,)"

  [1]=> string(110) "( "name" => "Bob","company" => "Target","haircolor" => 
 "red","name" => "Bbbb","home" => "Ohio","shoe" => 11.5)"
}

要将这两个字符串转换为父数组中的嵌套数组,似乎应该有一个php函数,但我似乎无法找到它。
我是否需要创建自己的功能才能完成此任务?

3 个答案:

答案 0 :(得分:2)

对第二个参数为true的字符串使用json_decode,并获得一个关联数组作为输出。

$url = "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats";
$arr = json_decode(file_get_contents($url), true);
Var_dump($arr);

见这里;
我从页面复制了字符串并将其发布为$ str。
https://3v4l.org/duWrI
只需要两个步骤。

答案 1 :(得分:1)

您的长字符串似乎是一个非常糟糕的数组存储自定义格式。使用json_encodeserialize来有效地存储数组(以及更多)将会更有效。

现在,如果您坚持使用它,可以执行此操作而不使用eval:

$long_string = '("name" => "Able","company" => "Tesla","haircolor" => 
"brown","name" => "Aaaa","home" => "Kansas","shoe" => 12,)<>( "name" => 
"Bob","company" => "Target","haircolor" => "red","name" => "Bbbb","home" => 
"Ohio","shoe" => 11.5)';
$parts = explode('<>', $long_string);
eval('$result = array(array' . $parts[0] . ', array' . $parts[1] . ');');
print_r($result);

无需说这是丑陋且非常不安全的,因为如果看起来像php代码就可以执行$ long_string。

另一种更安全的方法是手动解析字符串并从中构建一个数组。但它需要更多不那么简单的代码。再说一遍,如果你可以使用其他格式,那就去做吧。

答案 2 :(得分:0)

这完成了我所需要的: 从这里开始:http://php.net/manual/en/function.explode.php 例如:这是&#34; multi&#34;的功能。爆炸一个字符串。

<?php

$long_string = '"name" => "Able","company" => "Tesla","haircolor" => "brown","name" => "Aaaa","home" => "Kansas","shoe" => 12<>"name" => "Bob","company" => "Target","haircolor" => "red","name" => "Bbbb","home" =>"Ohio","shoe" => 11.5';

function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
// $string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
// $delimiters = Array(",",":","|","-");

$delimiters = Array("<>",",");

$res = multiexplode($delimiters,$long_string);
echo '<pre>';
print_r($res);
echo '</pre>';
?>