dongwusang0314 2014-07-06 02:50
浏览 16
已采纳

使用键PHP将字符串转换为数组

I am trying to take an array with delimited strings and turn it into a multi dimensional array with named keys. Its easy to do it with numbers for keys but in my case I want to assign a key to each. The keys are slug, title, and type which correspond to keys 0,1,2 in each array.

    array(
        'thisslug|This title|text',
        'thatslug|Thats title|text',
        'anotherslug|Another title|dropdown',
    );

I want to end up with

array(
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text')
),
  • 写回答

2条回答 默认 最新

  • doumi7854 2014-07-06 02:55
    关注
    $result = array();
    foreach ($array as $string) {
        $row = explode('|', $string); // Explode the string
        // Convert it to associative
        $result[] = array('slug' => $row[0], 'title' => $row[1], 'type' => $row[2]);
    }
    

    Or use array_combine:

    $keys = array('slug', 'title', 'type');
    foreach ($array as $string) {
        $row = explode('|', $string); // Explode the string 
        $result[] = array_combine($keys, $row);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探