Home > Software engineering >  How to trim a part of a string from a two-dimensional array php
How to trim a part of a string from a two-dimensional array php

Time:06-25

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

CodePudding user response:

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

  • Related