Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading