gpt4 book ai didi

php - 如何也将列设置为 Upper 并删除集合 laravel 中的符号 _

转载 作者:行者123 更新时间:2023-11-29 04:14:44 26 4
gpt4 key购买 nike

所以我想将列名和值设为大写

例子:

$collection = collect([
['name' => 'Sally'],
['school_name' => 'Arkansas'],
['age' => 28]
]);

$flattened = $collection->flatMap(function ($values) {
return array_map('strtoupper', $values);
});

$flattened->all();

// ['name' => 'SALLY', 'school_name' => 'ARKANSAS', 'age' => '28'];

我也想将 'name, school_name, age' 设为 Upper。该代码仅使值变为上层而不是列名

最佳答案

<?php

$arr = ['name' => 'Sally', 'school_name' => 'Arkansas', 'age' => '28'];

$out = [];
$replace = '';
array_walk($arr, function($val, $key) use (&$out, $replace) {
$key2 = strtoupper($key);
$key2 = str_replace('_', $replace, $key2);
$out[$key2] = strtoupper($val);
});

echo "before:\n";
print_r($arr);

echo "after:\n";
print_r($out);

给出结果:

before:
Array
(
[name] => Sally
[school_name] => Arkansas
[age] => 28
)
after:
Array
(
[NAME] => SALLY
[SCHOOLNAME] => ARKANSAS
[AGE] => 28
)

$replace 更改为您想要的任何字符或保留为空字符串以删除下划线。

PHP 手册引用:

  1. array_walk
  2. strtoupper
  3. str_replace
  4. Anonymous functions
  5. Passing by Reference

关于php - 如何也将列设置为 Upper 并删除集合 laravel 中的符号 _,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58812363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com