【问题标题】:how to convert a string into an array in php [duplicate]如何在php中将字符串转换为数组[重复]
【发布时间】:2023-04-03 14:08:01
【问题描述】:

如何在 PHP 中将字符串转换为数组?我有一个这样的字符串:

$str = "php/127/typescript/12/jquery/120/angular/50";

输出:

Array (
    [php]=> 127
    [typescript]=> 12
    [jquery]=> 120
    [angular]=> 50
)

【问题讨论】:

  • 自从关闭以来,我将一种简单的 PHP 方式作为对上述方式的回答。看看Split into segments and loop thru incrementing by two.。我想知道为什么所有人都在使用昂贵的正则表达式,当它是一个简单的 for 循环时。
  • @Markus Zeller 我正在给出你的评论和结果,那么为什么我要投反对票呢?
  • @KUMAR 我在写我的时候没有看到你的答案。否决票不是来自我。顺便说一句,您需要 count() - 1。当您过快发布错误答案时,您必须期待反对票。
  • @MarkusZeller count() - 1 不需要或技术上正确,for 循环正在检查小于 (<) 不小于或等于 (<=)。

标签: php


【解决方案1】:

您可以使用preg_match_all(正则表达式)和array_combine

使用的正则表达式:([^\/]*?)\/(\d+),解释here (by RegEx101)

$str = "php/127/typescript/12/jquery/120/angular/50";

#match string
preg_match_all("/([^\/]*?)\/(\d+)/", $str, $match);

#then combine match[1] and match[2] 
$result = array_combine($match[1], $match[2]);

print_r($result);

演示(带步骤):https://3v4l.org/blZhU

【讨论】:

    【解决方案2】:

    一种方法可能是使用preg_match_all 从路径中分别提取键和值。然后,使用array_combine 构建hashmap:

    $str = "php/127/typescript/12/jquery/120/angular/50";
    preg_match_all("/[^\W\d\/]+/", $str, $keys);
    preg_match_all("/\d+/", $str, $vals);
    $mapped = array_combine($keys[0], $vals[0]);
    print_r($mapped[0]);
    

    打印出来:

    Array
    (
        [0] => php
        [1] => typescript
        [2] => jquery
        [3] => angular
    )
    

    【讨论】:

    • 非常有用。感谢阅读和解决方案。代码之美。
    • Downvoter:虽然可能不是解决 this 问题的最佳方法,但可以很容易地想象这样一种情况,即对 preg_match_all 进行两次单独调用可能是有益的,例如如果键/值并不总是相邻,并且在整个路径字符串中是连续的。
    【解决方案3】:

    您可以将explode()for()Loop 一起使用,如下所示:-

    <?php
        
        $str = 'php/127/typescript/12/jquery/120/angular/50';
        $list = explode('/', $str);
        $list_count  = count($list);
    
        $result = array();
        for ($i=0 ; $i<$list_count; $i+=2) {
            $result[ $list[$i] ] = $list[$i+1];
        }
        
        print_r($result);
        ?>
    

    输出:-

     Array
        (
            [php] => 127
            [typescript] => 12
            [jquery] => 120
            [angular] => 50
        )
        
    

    在这里演示:- https://3v4l.org/8PQhd

    【讨论】:

    • 注意 count($list) 将在每次迭代中进行评估,您应该避免这样做,而是在循环之前将计数存储在变量中。
    • 好的,先生。我由答案编辑。
    • 非常有用。感谢阅读和解决方案。
    • 不适合我,它仍在阅读for ($i=0 ; $i&lt;count($list) ; $i+=2) {,而不是$count = count($list); for ($i=0 ; $i&lt;$count ; $i+=2) {
    • 先生,我更新了我的答案,你为什么不投票?
    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 2021-02-07
    • 2023-04-04
    • 2014-07-11
    • 1970-01-01
    • 2019-09-01
    • 2017-05-22
    相关资源
    最近更新 更多