将 "explode" 的输出从字符串转换为数组

Convert output of "explode" from strings to arrays

如何将"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 函数,但我似乎找不到它。
我是否需要创建自己的函数来完成此操作?

看来你的长字符串是一种很差的数组存储自定义格式。使用 json_encode or serialize 来有效地存储数组(以及更多)会更有效率。

现在,如果您坚持这样做,您可以不使用 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);

不用说这很丑陋而且很不安全,因为 $long_string 如果看起来像 php 代码就可以执行。

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

这完成了我需要的: 来自这里:http://php.net/manual/en/function.explode.php 示例:这是 "multi" 分解字符串的函数。

<?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>';
?>

在字符串上使用 json_decode,第二个参数为 true,您将得到一个关联数组作为输出。

$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
只需两步。