【问题标题】:How to get a particular part of associative array in php, laravel?如何在php,laravel中获取关联数组的特定部分?
【发布时间】:2019-03-28 10:37:51
【问题描述】:

我有类似的数组

$data = [
    'phone' => '9999999999',
    'body' => 'Sample Message',
    'caption' => 'Sample',
    'filename' => 'Sample File.PDF'
];

我想将数组中的特定部分放入另一个数组中,例如

$t_data = [
    'phone' => '9999999999',
    'body' => 'Sample Message'
];

怎么做? 而且应该是单行函数

【问题讨论】:

  • $t_data=array(); $t_data['phone']=$data['phone']; $t_data['body']=$data['body']; 这个问题太笼统了
  • 您好,请看guide how to ask good questions。到目前为止,您尝试过的是什么?
  • 我会做一些奇怪的事情,比如:$res = array_intersect_key($data, ['phone'=>0,'body'=>0])Sandbox。只是为了混淆初级开发人员,当他们必须为我记录它时...... :-D
  • 不是因为,我需要一个单行函数,就像我为这个问题标记的答案一样
  • 请把这个问题标记为无用的人改一下,把它当作一个请求,我认为它很有用,我还在下面标记了正确的答案。

标签: php arrays laravel arraylist associative-array


【解决方案1】:

你可以使用 laravel 助手 array_only():

$t_data = array_only($data, ["phone", "body"]);

【讨论】:

    【解决方案2】:

    如果你想取一个数组的一部分,你可以这样做:

    array_slice($data, 0, 2);
    

    它将从零位置开始取前两个值。

    【讨论】:

      【解决方案3】:

      试试这个

       $t_data = [
          'phone' =>$data['phone'],
          'body'=>$data['body']
      
       ];
      

      【讨论】:

        【解决方案4】:

        这样

        print_r(array_intersect_key($data, ['phone'=>0,'body'=>0]));
        

        输出

        Array
        (
            [phone] => 9999999999
            [body] => Sample Message
        )
        

        Sandbox

        或者作为一个函数

        function getArrayItems(array $array,$items,$separator=','){
             if(!is_array($items)) $items = array_filter(array_map('trim',explode($separator,$items)),function($i){
               return strlen($i);
             });
             return array_intersect_key($array, array_flip($items));
        }
        
        $data = [
            'phone' => '9999999999',
            'body' => 'Sample Message',
            'caption' => 'Sample',
            'filename' => 'Sample File.PDF'
        ];
        
        print_r(getArrayItems($data, 'body')); // returns [body=>'Sample Message']
        print_r(getArrayItems($data, ['body'])); // returns [body=>'Sample Message']
        print_r(getArrayItems($data, ['body','caption'])); // returns [body=>'Sample Message','caption' => 'Sample']
        print_r(getArrayItems($data, 'body,caption')); // returns [body=>'Sample Message','caption'=>'Sample']
        print_r(getArrayItems($data, ' body , caption ')); // returns [body=>'Sample Message','caption'=>'Sample']
        print_r(getArrayItems($data, 'body|caption','|')); // returns [body=>'Sample Message','caption'=>'Sample']
        

        Sandbox

        【讨论】:

          猜你喜欢
          • 2016-05-03
          • 2021-03-16
          • 1970-01-01
          • 2014-10-22
          • 2011-06-20
          • 1970-01-01
          • 1970-01-01
          • 2018-10-27
          • 2014-02-22
          相关资源
          最近更新 更多