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 用lstm来预测股票价格
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上