0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Uncaught TypeError: Argument 1 passed to cut String() must be of the type string
Do all the elements of $data have a 'name index? If not, add an if statement to check that it exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.