drb56625 2013-05-20 08:24
浏览 10
已采纳

爆炸字符串并在每4个实例后创建一个新数组

I have a string like this.

$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|";

I wish to explode the string into an array but create a new array every 4 instances of the pipe. also would be nice to name the keys as well like below.

eg:

    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
    )

And so on...

How can I go about achieving this?

  • 写回答

2条回答 默认 最新

  • dtoqa66028 2013-05-20 08:25
    关注

    You're looking for 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>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序