简体   繁体   中英

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

There is an array of $arr, you need to trim each element of ['name'] to the desired length and add arbitrary characters. I managed to do this with a regular array, but it doesn't work with a two-dimensional one

$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/',
    ],
];

Example of a function working with a regular array:

 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
);

it should turn out like this:

$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/',
    ],
];

Call cutString() only on the name` element, and assign that back to the element.

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM