1

我有一个这样的字符串。

$string = "title1|1.99|www.website.com|www.website.com/img1.jpg|title2|5.99|www.website2.com|www.website2.com/img2.jpg|title3|1.99|www.website3.com|www.website3.com/img3.jpg|";

我希望将字符串分解为一个数组,但每 4 个管道实例创建一个新数组。也可以很好地命名键,如下所示。

例如:

    array (
            [title] => title1
            [price] => 1.99
            [url] => www.website.com
            [gallery] => www.website.com/img1.jpg
  )

    array (
            [title] => title2
            [price] => 5.99
            [url] => www.website2.com
            [gallery] => www.website2.com/img2.jpg
    )

等等...

我怎样才能实现这一目标?

4

2 回答 2

4

您正在寻找array_chunk()

$string = 'title1|1.99|www.website.com|www.website.com/img1.jpg|title2|5.99|www.website2.com|www.website2.com/img2.jpg|title3|1.99|www.website3.com|www.website3.com/img3.jpg';

$keys = array('title', 'price', 'url', 'gallery');

$array = explode('|', $string);
$array = array_chunk($array, 4);

$array = array_map(function($array) use ($keys) {
    return array_combine($keys, $array);
}, $array);

echo '<pre>', print_r($array, true), '</pre>';
于 2013-05-20T08:25:22.537 回答
3

这是一种功能方法:

$string = "title1|1.99|www.website.com|www.website.com/img1.jpg|title2|5.99|www.website2.com|www.website2.com/img2.jpg|title3|1.99|www.website3.com|www.website3.com/img3.jpg";

$array = array_map(function($array) {
    return array(
        'title' => $array[0],
        'price' => $array[1],
        'url' => $array[2],
        'gallery' => $array[3]
    );
}, array_chunk(explode('|', $string), 4));

print_r($array);

输出:

Array
(
    [0] => Array
        (
            [title] => title1
            [price] => 1.99
            [url] => www.website.com
            [gallery] => www.website.com/img1.jpg
        )

    [1] => Array
        (
            [title] => title2
            [price] => 5.99
            [url] => www.website2.com
            [gallery] => www.website2.com/img2.jpg
        )

    [2] => Array
        (
            [title] => title3
            [price] => 1.99
            [url] => www.website3.com
            [gallery] => www.website3.com/img3.jpg
        )

)

|注意:我从字符串中删除了尾随。您需要这样做,否则会explode返回一个额外的空白字符串。

于 2013-05-20T08:30:32.023 回答