有一個 $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/',
],
];
uj5u.com熱心網友回復:
呼叫cutString() only on the name` 元素,并將其分配回元素。
$res = array_map(
function ($array) use ($length, $appends) {
if (isset($array['name'])) {
$array['name'] = cutString($array['name'], $length, $appends);
}
return $array;
},
$data
);
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496343.html
