doyz51819
2019-02-25 19:57 浏览 159
已采纳

PHP:如何从数组中的每个字符串中删除前两个字符?

Have:

[0] => 0-3019
[1] => 0-3020
[2] => 0-1031
[3] => 0-3021
[4] => 0-1004
[5] => 0-3011

Want:

[0] => 3019
[1] => 3020
[2] => 1031
[3] => 3021
[4] => 1004
[5] => 3011

Not sure how to get rid of it, tried this.

Edit: Here is the code I've tried:

$files = array_keys($_FILES);

foreach ($files AS $f) {
    $f = substr($f,2);
}

For some reason it works inside the forloop but isn't actually saving each element as the substring version of itself :(

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    douzhuo1853 douzhuo1853 2019-02-25 20:26

    You can reference & each exposed element in order to change the original:

    foreach ($files as &$f) {
        $f = substr($f, 2);
    }
    

    Or modify the original array using the key:

    foreach ($files as $k => $f) {
        $files[$k] = substr($f, 2);
    }
    
    点赞 评论 复制链接分享
  • duandaiqin6080 duandaiqin6080 2019-02-25 20:16

    Let's say the name of your array is $elements, you can loop through each element of the array and use the PHP substr to replace the current value with a portion of the string.

    What substr($string, $start, $length) does is take a part of the string $string with a length of $length starting from $start.

    <?php
    foreach ($elements as $index=>$element) {
        $elements[$index] = substr($element, 2);
    }
    ?>
    

    UPDATE

    If it's the index that needs changind, you can do the following:

    <?php
    foreach ($elements as $index=>$element) {
        $new_index = substr($index, 2);
        $elements[$new_index] = $element;
    
        unset($elements[$index]);
    }
    ?>
    
    点赞 评论 复制链接分享

相关推荐