热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为PHP开发者设计,能够根据指定的数组操作类型生成专业、准确的PHP代码实现。通过结构化的工作流程,确保代码符合最佳实践,包含完整注释和错误处理机制。支持排序、增删、合并等常见数组操作,输出格式规范统一,帮助开发者快速获得可直接使用的代码解决方案,提升开发效率。
代码功能说明 本代码根据给定规则对商品数组进行排序,保留外层关联键(SKU):
先按 price 降序排序;
price 为空或非数值的商品排在末尾;
同价时按 stock 降序;
再按 name 升序;
排序后返回保持 SKU 键的数组。
完整的PHP代码块
<?php
declare(strict_types=1);
/**
* 按规则对商品数组排序(保留外层关联键)
*
* 规则:
* 1) price 数值在前(按降序),price 为空或非数值在后;
* 2) 同价时按 stock 降序;
* 3) 再按 name 升序;
*
* @param array<string,array{name?:mixed,price?:mixed,stock?:mixed}> $products
* @return array<string,array{name?:mixed,price?:mixed,stock?:mixed}>
*/
function sortProductsByRules(array $products): array
{
// 复制一份,避免原数组被直接修改
$sorted = $products;
// 将 price 转为有效数值(float),无效返回 null
$toValidPrice = static function ($value): ?float {
if ($value === null || $value === '') {
return null;
}
if (!is_numeric($value)) {
return null;
}
$num = (float)$value;
if (!is_finite($num)) {
return null;
}
return $num;
};
// 统一获取库存为整数;非数值视为 0
$toStock = static function ($value): int {
return is_numeric($value) ? (int)$value : 0;
};
// 统一获取名称为字符串
$toName = static function ($value): string {
return is_string($value) ? $value : '';
};
// 使用 uasort 保留外层键(SKU)
uasort($sorted, static function (array $a, array $b) use ($toValidPrice, $toStock, $toName): int {
$priceA = $toValidPrice($a['price'] ?? null);
$priceB = $toValidPrice($b['price'] ?? null);
// 1) 价格是否有效(有效在前,无效在后)
$aHasPrice = ($priceA !== null);
$bHasPrice = ($priceB !== null);
if ($aHasPrice && $bHasPrice) {
// 价格都有效:按 price 降序
if ($priceA < $priceB) {
return 1;
}
if ($priceA > $priceB) {
return -1;
}
// 价格相同,继续比库存
} elseif ($aHasPrice && !$bHasPrice) {
return -1; // A 在前
} elseif (!$aHasPrice && $bHasPrice) {
return 1; // B 在前
} // 两者都无效,继续比库存与名称
// 2) 同价(或都无效)时按 stock 降序
$stockA = $toStock($a['stock'] ?? 0);
$stockB = $toStock($b['stock'] ?? 0);
if ($stockA !== $stockB) {
return $stockB <=> $stockA; // 降序
}
// 3) 再按 name 升序
$nameA = $toName($a['name'] ?? '');
$nameB = $toName($b['name'] ?? '');
$byName = strnatcmp($nameA, $nameB); // 自然排序,升序
return $byName <=> 0;
});
return $sorted;
}
// ===================== 使用示例 =====================
$products = [
'A100' => ['name' => 'USB线', 'price' => 19.9, 'stock' => 120],
'B200' => ['name' => '键盘', 'price' => '99', 'stock' => 30],
'C300' => ['name' => '耳机', 'price' => null, 'stock' => 50],
'D400' => ['name' => '散热器', 'price' => 99, 'stock' => 35],
'E500' => ['name' => '转接头', 'price' => 'invalid', 'stock' => 0],
];
$sorted = sortProductsByRules($products);
// 输出效果演示(保留 SKU 键)
echo "排序结果:\n";
print_r($sorted);
/*
期望排序顺序(SKU):
1) D400(price 99, stock 35)
2) B200(price 99, stock 30)
3) A100(price 19.9, stock 120)
4) C300(price 无效, stock 50)
5) E500(price 无效, stock 0)
*/
关键代码注释
使用 uasort 对关联数组进行自定义排序,能保持外层键(SKU)。
toValidPrice:用 is_numeric 判断可转数值的字符串(如 '99'),并排除 null、空字符串与非有限值,保证 price 比较的安全性与准确性。
比较函数逻辑:
使用示例和注意事项
示例代码直接可运行,输出的数组保持原有 SKU 键。
名称排序使用 strnatcmp(自然排序),中文会按字节序比较;如需更符合本地化的中文拼音/笔画排序,可使用 intl 扩展的 Collator,但这会引入额外依赖。
uasort 的比较器已给出完整的平局规则(stock、name),确保排序结果稳定可复现。
如果某些商品缺少 price/stock/name 字段,代码会使用安全的默认值(price 视为无效、stock 视为 0、name 视为 ''),避免 Notice。
相关函数说明
uasort(array &$array, callable $callback):使用用户自定义比较函数对数组进行排序,同时保留键名(适合对关联数组排序)。
is_numeric(mixed $var):判断是否为数字或数字字符串(如 '99')。
is_finite(float $num):检查数值是否为有限数(排除 INF、-INF、NAN)。
strnatcmp(string $str1, string $str2):使用“自然排序”算法比较字符串,适合包含数字的字符串比较。
太空船运算符 <=>:三路比较运算符,返回 -1、0、1,代码中用于简化降序/升序比较表达式。
Merge two order lists, deduplicate by order_id, keep the one with the newer updated_at when duplicated, then sort the final result by created_at ascending. The implementation validates required fields, safely parses date strings, and provides deterministic tie-breaking.
<?php
declare(strict_types=1);
/**
* Merge two order lists, deduplicate by order_id (keeping the newer updated_at),
* then sort by created_at ascending (tie-breakers: updated_at, order_id).
*
* Assumptions:
* - Date strings are in "Y-m-d H:i" or "Y-m-d H:i:s".
* - Timezone is forced to UTC for deterministic comparison across environments.
*
* @param array<int,array<string,mixed>> $left
* @param array<int,array<string,mixed>> $right
* @return array<int,array<string,mixed>>
*/
function mergeOrders(array $left, array $right): array
{
$index = []; // order_id => ['item' => array, 'created_ts' => int, 'updated_ts' => int]
foreach (array_merge($left, $right) as $row) {
// Basic shape validation
if (!is_array($row)) {
error_log('mergeOrders: skipped non-array row');
continue;
}
if (!isset($row['order_id'], $row['created_at'], $row['updated_at'])) {
error_log('mergeOrders: skipped row missing required keys: ' . json_encode($row, JSON_UNESCAPED_UNICODE));
continue;
}
$orderId = (string)$row['order_id'];
if ($orderId === '') {
error_log('mergeOrders: skipped row with empty order_id');
continue;
}
// Parse dates strictly to timestamps (UTC)
try {
$createdTs = parseTimestampStrict((string)$row['created_at']);
$updatedTs = parseTimestampStrict((string)$row['updated_at']);
} catch (InvalidArgumentException $e) {
error_log('mergeOrders: skipped row with invalid date/time: ' . $e->getMessage());
continue;
}
// Deduplicate by keeping the item with the newer updated_at.
// On exact updated_at ties, prefer the later encountered row (right-hand list wins due to iteration order).
if (!isset($index[$orderId])) {
$index[$orderId] = [
'item' => $row,
'created_ts' => $createdTs,
'updated_ts' => $updatedTs,
];
continue;
}
$existing = $index[$orderId];
if ($updatedTs > $existing['updated_ts'] || $updatedTs === $existing['updated_ts']) {
$index[$orderId] = [
'item' => $row,
'created_ts' => $createdTs,
'updated_ts' => $updatedTs,
];
}
}
// Sort by created_at ASC, then updated_at ASC, then order_id ASC (deterministic)
$entries = array_values($index);
usort($entries, static function (array $a, array $b): int {
if ($a['created_ts'] < $b['created_ts']) return -1;
if ($a['created_ts'] > $b['created_ts']) return 1;
if ($a['updated_ts'] < $b['updated_ts']) return -1;
if ($a['updated_ts'] > $b['updated_ts']) return 1;
return strcmp((string)$a['item']['order_id'], (string)$b['item']['order_id']);
});
// Return only the original items
return array_map(static fn(array $e) => $e['item'], $entries);
}
/**
* Strictly parse a date string to a Unix timestamp in UTC.
* Accepts "Y-m-d H:i:s" or "Y-m-d H:i".
*
* @throws InvalidArgumentException
*/
function parseTimestampStrict(string $value): int
{
static $tz = null;
$tz ??= new DateTimeZone('UTC');
$formats = ['Y-m-d H:i:s', 'Y-m-d H:i'];
foreach ($formats as $fmt) {
$dt = DateTimeImmutable::createFromFormat($fmt, $value, $tz);
if ($dt instanceof DateTimeImmutable) {
$errors = DateTimeImmutable::getLastErrors();
$hasNoErrors = ($errors['warning_count'] ?? 0) === 0 && ($errors['error_count'] ?? 0) === 0;
if ($hasNoErrors) {
return $dt->getTimestamp();
}
}
}
throw new InvalidArgumentException("Invalid date/time format: {$value}");
}
/* ---------------------- Usage Example ---------------------- */
$pendingOrders = [
['order_id' => 'O-001', 'created_at' => '2025-05-01 10:00', 'updated_at' => '2025-05-01 10:00', 'status' => 'pending'],
['order_id' => 'O-002', 'created_at' => '2025-05-02 09:20', 'updated_at' => '2025-05-03 08:00', 'status' => 'pending'],
];
$newOrders = [
['order_id' => 'O-002', 'created_at' => '2025-05-02 09:20', 'updated_at' => '2025-05-04 12:30', 'status' => 'paid'],
['order_id' => 'O-003', 'created_at' => '2025-05-04 08:15', 'updated_at' => '2025-05-04 08:15', 'status' => 'pending'],
];
$result = mergeOrders($pendingOrders, $newOrders);
// For demonstration:
print_r($result);
/*
Expected $result (sorted by created_at ASC):
Array
(
[0] => Array
(
[order_id] => O-001
[created_at] => 2025-05-01 10:00
[updated_at] => 2025-05-01 10:00
[status] => pending
)
[1] => Array
(
[order_id] => O-002
[created_at] => 2025-05-02 09:20
[updated_at] => 2025-05-04 12:30
[status] => paid
)
[2] => Array
(
[order_id] => O-003
[created_at] => 2025-05-04 08:15
[updated_at] => 2025-05-04 08:15
[status] => pending
)
)
*/
<?php
declare(strict_types=1);
/**
* 根据规则过滤用户数组:
* - active === true
* - last_login_at 在最近 $days 天内(含当天),且不晚于当前时间
* - roles 包含 'editor' 或 'admin'
* - 缺失字段或类型不符合的项被忽略
* - 保持原索引
*
* @param array $users
* @param int $days 最近天数,必须为非负数
* @param DateTimeZone|null $tz 可选时区(不指定则使用 php.ini 默认时区)
* @return array 过滤后的用户数组(保留原索引)
*/
function filterActiveRecentlyLoggedUsers(array $users, int $days = 30, ?DateTimeZone $tz = null): array
{
// 归一化 days,避免负值带来的意外逻辑
$days = max(0, $days);
// 当前时间(可选时区)
$now = $tz instanceof DateTimeZone
? new DateTimeImmutable('now', $tz)
: new DateTimeImmutable('now');
// 最近 $days 天的阈值(含边界)
$threshold = $now->sub(new DateInterval('P' . $days . 'D'));
// 允许的角色
$allowedRoles = ['editor', 'admin'];
return array_filter($users, function ($user) use ($now, $threshold, $allowedRoles): bool {
// 必须是数组
if (!is_array($user)) {
return false;
}
// 检查必需字段是否存在:active, last_login_at, roles
foreach (['active', 'last_login_at', 'roles'] as $key) {
if (!array_key_exists($key, $user)) {
return false; // 忽略缺失字段的项
}
}
// active 必须严格为 true
if ($user['active'] !== true) {
return false;
}
// roles 必须为数组,且包含 'editor' 或 'admin'
if (!is_array($user['roles']) || empty(array_intersect($allowedRoles, $user['roles']))) {
return false;
}
// 校验并解析 last_login_at(期望格式:Y-m-d)
$dateStr = (string)$user['last_login_at'];
$loginAt = DateTimeImmutable::createFromFormat('Y-m-d', $dateStr);
// 检查解析错误(避免宽松解析)
$errors = DateTime::getLastErrors();
$hasErrors = $errors && (($errors['warning_count'] ?? 0) > 0 || ($errors['error_count'] ?? 0) > 0);
if (!$loginAt || $hasErrors) {
return false;
}
// last_login_at 不得晚于现在,且需在最近 N 天内(含边界)
if ($loginAt > $now) {
return false;
}
if ($loginAt < $threshold) {
return false;
}
return true;
});
}
// ---------------- 使用示例 ----------------
$users = [
['id' => 1, 'name' => 'Lily', 'roles' => ['viewer','editor'], 'active' => true, 'last_login_at' => '2025-11-28'],
['id' => 2, 'name' => 'Max', 'roles' => ['viewer'], 'active' => true, 'last_login_at' => '2025-07-12'],
['id' => 3, 'name' => 'Chen', 'roles' => ['admin'], 'active' => false, 'last_login_at' => '2025-12-01'],
['id' => 4, 'name' => 'Iris', 'roles' => ['editor'], 'active' => true, 'last_login_at' => '2025-12-05'],
];
// 示例:过滤最近 30 天内的活跃且拥有 editor/admin 角色的用户(保留原索引)
$result = filterActiveRecentlyLoggedUsers($users, 30);
// 输出结果(注意保留了原索引 0 和 3)
echo var_export($result, true), PHP_EOL;
示例输出(var_export)示意: array ( 0 => array ( 'id' => 1, 'name' => 'Lily', 'roles' => array ( 0 => 'viewer', 1 => 'editor', ), 'active' => true, 'last_login_at' => '2025-11-28', ), 3 => array ( 'id' => 4, 'name' => 'Iris', 'roles' => array ( 0 => 'editor', ), 'active' => true, 'last_login_at' => '2025-12-05', ), )
把对“数组要怎么处理”的口头需求,快速转化为可直接粘贴运行的高质量PHP代码;覆盖排序、增删、合并等常见操作,并自动补齐注释与边界处理,让代码更稳、更易读;统一输出结构与命名风格,缩短评审时间、降低返工;适用于日常开发、教学演示、代码审查与脚手架搭建,帮助个人与团队在数分钟内完成过去需要反复搜索与试错的工作;试用即可体验秒级产出,付费可解锁自定义风格、团队模板库、批量生成、多语言注释与优先支持等增值能力,持续放大效率收益。
在需求开发中,按操作类型快速生成数组处理函数与示例,自带边界检查与注释,减少查阅资料时间,缩短提测周期。
通过“思路说明+完整代码+注意事项”的输出理解语法与常见坑点,照着练习即可完成作业、小项目与练手题。
用统一规范产出参考实现,制定团队基线;评审时对照示例核对异常处理与命名风格,快速发现风险点。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期