簡體   English   中英

如何從二維數組php中修剪字符串的一部分

[英]How to trim a part of a string from a two-dimensional array php

有一個 $arr 數組,你需要將 ['name'] 的每個元素修剪到所需的長度並添加任意字符。 我設法用常規數組做到了這一點,但它不適用於二維數組

$arr = [
    [
        'name' => 'Home page',
        'sort' => 1,
        'path' => '/',
    ],
    [
        'name' => 'Сatalog',
        'sort' => 110,
        'path' => '/catalog/',
    ],
    [
        'name' => 'Set of letters 1',
        'sort' => 10,
        'path' => '/section1/',
    ],
    [
        'name' => 'Set of letters 2',
        'sort' => 9,
        'path' => '/section2/',
    ],
    [
        'name' => 'Set of letters 3',
        'sort' => 9200,
        'path' => '/section3/',
    ],
];

使用常規數組的函數示例:

 function cutString(string $string, int $length, string $appends)
{
    if (mb_strlen($string) < $length) {
        return $string;
    }
    return mb_strimwidth($string, 0, $length) . $appends;
}

$res = array_map(
    function ($string) use ($length, $appends) {
        return cutString($string, 5, '...');
    },
    $data
);

結果應該是這樣的:

$arr = [
    [
        'name' => 'Home ...',
        'sort' => 1,
        'path' => '/',
    ],
    [
        'name' => 'Сatal...',
        'sort' => 110,
        'path' => '/catalog/',
    ],
    [
        'name' => 'Set o...',
        'sort' => 10,
        'path' => '/section1/',
    ],
    [
        'name' => 'Set o...',
        'sort' => 9,
        'path' => '/section2/',
    ],
    [
        'name' => 'Set o...',
        'sort' => 9200,
        'path' => '/section3/',
    ],
];

cutString() only on the並將其分配回元素。

$res = array_map(
    function ($array) use ($length, $appends) {
        if (isset($array['name'])) {
            $array['name'] = cutString($array['name'], $length, $appends);
        }
        return $array;
    },
    $data
);

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM