dongshou1991 2019-03-21 08:12
浏览 114
已采纳

如何从数组内的值中修剪数据?

This is my data:

$d = $request->request->get('data');

The output:

[{"name":"form[id]","value":"10"},{"name":"form[name]","value":"Telefon2"},{"name":"form[uuid]","value":"bb80878ad4"},{"name":"form[productgroup]","value":"6"},{"name":"form[category]","value":"1"},{"name":"form[documents]","value":"7"}

I want to create a new array, that is removing extracting the variable inside the brackets.

 function trim($d) {
          preg_match('#\[(.*?)\]#', $d, $match);
          return $match[1];
   }


$dData = array_combine(array_column(trim($d), 'name'), array_column($d, 'value'));
$json = json_encode($dData);

But the error is

Warning: preg_match() expects parameter 2 to be string, array given

  • 写回答

2条回答 默认 最新

  • doubi7739 2019-03-21 08:26
    关注

    You're going to need to do a few things before you begin.

    Firstly, rename the trim function to something like extract_name because PHP already has a built in trim function that removes whitespace from a string - or any character present in the character mask.
    Secondly, you are going to need to iterate over each of the elements in the name column. You will notice the error you are getting from preg_match is because you are passing all values in one go.
    Thirdly, I am assuming that the value of $d is an array of PHP objects. This is done, and assumed, in my solution using $d = json_decode($d);.

    Using array_map instead of a foreach means we can have a nice one liner:

    function extract_name($d) {
        preg_match('#\[(.*?)\]#', $d, $match);
        return $match[1];
    }
    
    $dData = array_combine(array_map('extract_name', array_column($d, 'name')), array_column($d, 'value'));
    

    The output being:

    array:6 [
      "id" => "10"
      "name" => "Telefon2"
      "uuid" => "bb80878ad4"
      "productgroup" => "6"
      "category" => "1"
      "documents" => "7"
    ]
    

    Live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: