dopnpoh056622 2012-01-19 16:18
浏览 28
已采纳

PHP组数组的值

I have an array like this:

Array ( 
     [0] => ing_1_ing 
     [1] => ing_1_amount 
     [2] => ing_1_det 
     [3] => ing_1_meas
     [4] => ing_2_ing 
     [5] => ing_2_amount 
     [6] => ing_2_det 
     [7] => ing_2_meas 
)

And I want to group the values into an array like this:

Array (
   [0] => Array(
             [0] => ing_1_ing
             [1] => ing_1_amount
             [2] => ing_1_det
             [3] => ing_1_meas
          )
   [1] => Array(
             [0] => ing_2_ing
             [1] => ing_2_amount
             [2] => ing_2_det
             [3] => ing_2_meas
          )
)

There may be many other items named like that: ing_NUMBER_type

How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:

$i = 1;     
foreach ($firstArray as $t) {
            if (strpos($t, (string)$i)) {
                $secondArray[--$i][] = $t;
            } else {
                $i++;
            }
        }

What is wrong? Can you advice?

  • 写回答

3条回答 默认 最新

  • donglei_0507 2012-01-19 16:30
    关注

    It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:

    $result = array();
    
    foreach ($firstArray as $value)
    {
        $n = sscanf($value, 'ing_%d_%s', $id, $string);
    
        if ($n > 1)
        {
            $result[$id][] = $value;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图