dpiuqwwyu187975836 2019-03-17 15:28
浏览 66
已采纳

如何将字符串转换为int并逐字符地将它们拆分为另一个数组

Using this function,prt_pattern("341","0"), to print out

 0 
00 
00 
000

I'm stuck at converting "341" into integer and store it each number the following was the result i wanted

array[0] = 3
array[1] = 4
array[2] = 1

The flow I'm going to plan for this function is, convert string into int and store it by character, and then find the highest value. After that using 2 for loop, 1st for loop is loop from largest number to 1 and 2nd loop is for looping the number if 4 = 4, print 0 else print " " and value at array[1] -= 1.

Hope anyone can help me with this.

  • 写回答

1条回答 默认 最新

  • doukuipei9938 2019-03-17 15:40
    关注

    This should work. First I create an array of each number inside the string (cast to integer), then find the highest number from it using the max function.

    <?php
    $array = (function ($str): array {
        $a = [];
        $strlen = strlen($str);
        for($i = 0; $i < $strlen; $i++) {
            $a[] = (int) $str[$i];
        }
        return $a;
    })("3429");
    
    
    var_dump($array);
    
    /**
    array(4) {
      [0]=>
      int(3)
      [1]=>
      int(4)
      [2]=>
      int(2)
      [3]=>
      int(9)
    }
    **/
    
    var_dump(max($array)); //int(9)
    

    Test it online here : http://sandbox.onlinephpfunctions.com/code/2e3446d4475c3d69215857ed33a2c1f94f628e0b

    edit

    As Barmar pointed out in the comments, its way easier to use PHPs function str_split like so:

    $array = str_split("3429");
    

    Which will create an array just like previous mentioned.

    (I feel silly for not thinking of that function.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大