Quellcode durchsuchen

数组帮助函数增加:驼峰/下划线 互转

shizhongqi vor 4 Jahren
Ursprung
Commit
596822cf13
2 geänderte Dateien mit 36 neuen und 1 gelöschten Zeilen
  1. 4 1
      app-hd/controllers/MtController.php
  2. 32 0
      common/components/arrayUtil.php

+ 4 - 1
app-hd/controllers/MtController.php

@@ -3,6 +3,7 @@
 namespace hd\controllers;
 
 use bizHd\meituan\classes\MtOrderClass;
+use common\components\arrayUtil;
 use Yii;
 use Abbotton\MeituanTakeaway\Application;
 use yii\helpers\Json;
@@ -30,7 +31,9 @@ class MtController extends PublicController
             return Json::encode(['data' => 'ok']);
         }
 
-        $mtOrder = MtOrderClass::add($post);
+        //2022-07-09 22:37:23 [101.236.11.53][-][-][warning][application] model validate errors: {"orderId":["Order Id cannot be blank."],"orderPhoneNumber":["Order Phone Number cannot be blank."],"recipientName":["Recipient Name cannot be blank."],"recipientPhone":["Recipient Phone cannot be blank."],"recipientAddress":["Recipient Address cannot be blank."],"updated_at":["Updated At cannot be blank."]}
+        $data = arrayUtil::humpUnderlineConversion($post, 1);
+        $mtOrder = MtOrderClass::add($data);
         return Json::encode(['data' => 'ok']);
 
         $app = new Application($this->config);

+ 32 - 0
common/components/arrayUtil.php

@@ -94,4 +94,36 @@ class arrayUtil
     {
         return array_unique(array_filter(array_column($arr, $col)));
     }
+
+    /**
+     * 描述:驼峰/下划线 互转
+     * 参数:{
+     *     "params": "待转换数组",
+     *     "type": "默认 0: 驼峰-》下划线;1:下划线-》驼峰"
+     * }
+     */
+    public static function humpUnderlineConversion($params, $type = 0) {
+        $newArr = [];
+        if (!is_array($params) || empty($params)) return $newArr;
+        foreach ($params as $key => $val){
+            if ($type == 1) {
+                $newkey = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
+                    return strtoupper($matches[2]);
+                }, $key);
+            } else {
+                $newkey = $key;
+                if (!strstr($key, '_')) {
+                    $key = str_replace("_", "", $key);
+                    $key = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
+                        return '_' . strtolower($matches[0]);
+                    }, $key);
+                    $newkey = ltrim($key, "_");
+                }
+            }
+
+            $newArr[$newkey] = is_array($val) ? self::humpUnderlineConversion($val, $type) : $val;
+        }
+
+        return $newArr;
+    }
 }