¥
立即购买

PHP数组操作代码生成器

0 浏览
0 试用
0 购买
Dec 10, 2025更新

本提示词专为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 比较的安全性与准确性。

  • 比较函数逻辑:

    • 先比较 price 是否有效(有效在前,无效在后);
    • price 都有效则按 price 降序;
    • 同价或都无效时,按 stock 降序;
    • 再按 name 自然排序升序,保证结果确定性。
  • 使用示例和注意事项

  • 示例代码直接可运行,输出的数组保持原有 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,代码中用于简化降序/升序比较表达式。

Function overview

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.

Complete PHP code

<?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
        )
)
*/

Key code notes

  • Deduplication map: Uses an associative index keyed by order_id to ensure O(1) replacement checks.
  • Tie-breaking on duplicates: If updated_at timestamps are equal, the later encountered item replaces the previous one. Because we iterate array_merge($left, $right), items from the right-hand list win on ties.
  • Deterministic sorting: usort comparator orders by created_at, then updated_at, then order_id to avoid non-deterministic order when timestamps are equal.
  • Strict date parsing: parseTimestampStrict validates input against known formats and normalizes to UTC for consistency across environments. Invalid rows are safely skipped with error_log diagnostics.

Usage and notes

  • Input validation: Rows missing order_id, created_at, or updated_at, or with unparseable dates, are skipped rather than causing runtime errors. Adjust this behavior if you prefer exceptions.
  • Timezone: UTC is used for parsing to avoid environment-specific differences. If your data is in a specific timezone, adjust the DateTimeZone accordingly.
  • Complexity: O((n + m) log u), where n, m are input sizes and u is the number of unique order_ids.
  • array_merge: Concatenates two indexed arrays while preserving order.
  • usort: Sorts an array with a user-defined comparison function.
  • DateTimeImmutable::createFromFormat: Parses a date/time string per a specified format.
  • DateTimeImmutable::getLastErrors: Retrieves detailed parsing errors/warnings for validation.
  • strcmp: Performs a binary-safe string comparison, used for deterministic tie-breaking.
  • array_values: Reindexes an array to consecutive numeric keys.
  • array_map: Transforms arrays; here, it extracts the original item from helper entries.

代码功能说明

  • 对用户数组进行筛选(filter),规则如下:
    • active 为 true(严格布尔值)
    • last_login_at 在最近 N 天内(默认 30 天),且不晚于当前时间
    • roles 至少包含 'editor' 或 'admin'
  • 忽略缺失字段或字段类型不符合要求的项
  • 过滤后保持原数组索引不变(不重新索引)

完整的PHP代码块

<?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;

关键代码注释

  • 使用 array_filter 进行筛选,默认会保留原有数组的键,不会重新索引,满足“保持原索引”的要求。
  • 使用 DateTimeImmutable + DateInterval 计算“最近 N 天”的时间阈值,避免字符串时间操作的不确定性。
  • 使用 DateTimeImmutable::createFromFormat('Y-m-d', $str) 严格解析日期,并通过 DateTime::getLastErrors() 防止宽松解析(如 2025-13-40 被自动修正)。
  • 对 active 做严格布尔判断(=== true),防止 "1"/1 被误当作 true。
  • 对 roles 使用 array_intersect 判断是否包含 'editor' 或 'admin' 中的任意一个。

使用示例和注意事项

  • 以上示例在当前日期为 2025-12-10 时,结果将包含索引 0(Lily)和 3(Iris),因为这两项满足全部条件且在最近 30 天内。
  • 注意事项:
    • last_login_at 需要是 Y-m-d 格式,且不应晚于当前时间。
    • roles 区分大小写,如果数据源可能大小写不一致,可在过滤前统一转为小写。
    • 如需改变“最近天数”,修改函数第二个参数 $days 即可。
    • 如需统一时区(避免服务器默认时区差异),可传入第三个参数 DateTimeZone,例如 new DateTimeZone('UTC')。
    • 若需要在最终结果中重排索引,可在结果外层调用 array_values();本实现默认保留原索引以满足题意。

示例输出(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', ), )


相关函数说明

  • array_filter(array $array, callable $callback = null, int $mode = 0): array
    • 使用回调函数过滤数组元素;默认保留原有键名(索引)。
  • array_intersect(array $array, array ...$arrays): array
    • 计算数组的交集,用于判断 roles 是否包含指定角色之一。
  • DateTimeImmutable::__construct(string $datetime = "now", ?DateTimeZone $timezone = null)
    • 创建不可变日期时间对象,避免副作用。
  • DateInterval
    • 表示时间间隔;配合 sub/add 计算阈值(如 P30D 表示 30 天)。
  • DateTimeImmutable::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
    • 按指定格式解析日期字符串。
  • DateTime::getLastErrors(): array|false
    • 获取最近一次日期时间解析的错误与警告,用于严格校验日期格式有效性。

示例详情

解决的问题

把对“数组要怎么处理”的口头需求,快速转化为可直接粘贴运行的高质量PHP代码;覆盖排序、增删、合并等常见操作,并自动补齐注释与边界处理,让代码更稳、更易读;统一输出结构与命名风格,缩短评审时间、降低返工;适用于日常开发、教学演示、代码审查与脚手架搭建,帮助个人与团队在数分钟内完成过去需要反复搜索与试错的工作;试用即可体验秒级产出,付费可解锁自定义风格、团队模板库、批量生成、多语言注释与优先支持等增值能力,持续放大效率收益。

适用用户

PHP后端工程师

在需求开发中,按操作类型快速生成数组处理函数与示例,自带边界检查与注释,减少查阅资料时间,缩短提测周期。

初学者与转语言开发者

通过“思路说明+完整代码+注意事项”的输出理解语法与常见坑点,照着练习即可完成作业、小项目与练手题。

技术负责人/代码审查者

用统一规范产出参考实现,制定团队基线;评审时对照示例核对异常处理与命名风格,快速发现风险点。

特征总结

一键生成排序、增删、合并等数组代码,附完整注释,复制即用,显著压缩开发时间
自动补齐边界与错误处理,涵盖空数组、非法输入等场景,减少线上故障与返工成本
按操作类型与数据模板化配置,所见即所得,避免反复查文档与手写样板代码
生成结构统一的说明、示例与注意事项,便于团队评审、知识沉淀与跨项目复用
遵循主流版本最佳实践与安全规范,规避过时函数,降低技术债与兼容性风险
支持多场景讲解式输出,先解释思路再给代码,新人上手快,培训与交付更顺畅
可快速切换不同实现思路与优化建议,便于对比性能取舍,选出更稳更快的方案
内置可阅读的关键注释与命名风格,提升代码可维护性,后续扩展与接手更轻松
一键复用生成模板进行批量改造,适合迁移重构与迭代更新,保持团队风格一致

如何使用购买的提示词模板

1. 直接在外部 Chat 应用中使用

将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。

2. 发布为 API 接口调用

把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。

3. 在 MCP Client 中配置使用

在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。

AI 提示词价格
¥20.00元
先用后买,用好了再付款,超安全!

您购买后可以获得什么

获得完整提示词模板
- 共 460 tokens
- 3 个可调节参数
{ 操作类型 } { 数组数据 } { 输出语言 }
获得社区贡献内容的使用权
- 精选社区优质案例,助您快速上手提示词
使用提示词兑换券,低至 ¥ 9.9
了解兑换券 →
限时半价

不要错过!

半价获取高级提示词-优惠即将到期

17
:
23
小时
:
59
分钟
:
59