在不使用循环的情况下将字符串分解为关联数组? [英] Explode a string to associative array without using loops?

查看:20
本文介绍了在不使用循环的情况下将字符串分解为关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像 1-350,9-390.99,... 这样的字符串,我需要把它变成这样的关联数组:

I have a string like 1-350,9-390.99,..., and I need to turn it into an associative array like this:

 Array
    (
        [1] => 350
        [9] => 390.99
        ...........
    )

是否可以只使用数组函数而不使用循环来做到这一点?

Is it possible to do this using only array functions, without a loop?

推荐答案

这是一种不用 for 循环的方法,使用 array_walk:

Here's a way to do it without a for loop, using array_walk:

$array = explode(',', $string);
$new_array = array();
array_walk($array,'walk', $new_array);

function walk($val, $key, &$new_array){
    $nums = explode('-',$val);
    $new_array[$nums[0]] = $nums[1];
}

Ideone.com 的示例.

这篇关于在不使用循环的情况下将字符串分解为关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆