根据需要修剪数组

时间:2018-01-05 07:13:17

标签: php arrays

我在提交表格

时得到以下数组
[_wpcf7] => 3
[_wpcf7_version] => 4.9.2
[_wpcf7_locale] => en_US
[_wpcf7_unit_tag] => wpcf7-f3-p2-o1
[_wpcf7_container_post] => 2
[your-name] => sad
[your-subject] => sad
[your-message] => sdsa

但是我需要将它修剪并移动到另一个数组,如

[your-name] => sad
[your-subject] => sad
[your-message] => sdsa

其实我需要删除数组的内容

[_wpcf7] => 3
[_wpcf7_version] => 4.9.2
[_wpcf7_locale] => en_US
[_wpcf7_unit_tag] => wpcf7-f3-p2-o1
[_wpcf7_container_post] => 2

所以请指导我如何使用PHP脚本

来完成它

4 个答案:

答案 0 :(得分:1)

仅在数组中保存所需的键

$array2 = array(
 'your-name',
 'your-subject',
 'your-message',
);

$res = array_intersect_key($array1, array_flip($array2));

demo

答案 1 :(得分:0)

试试这段代码:

$array2 = array(
 'your-name' => $array1['your-name'],
 'your-subject' => $array1['your-subject'],
 'your-message' => $array1['your-message'],
);

答案 2 :(得分:0)

如果始终是最后三项(您在评论中确认),则可以使用此代码 它将首先获取所有键名,然后向后循环键三次以获取最后三项并将其保存到$namearr

$arr = ["_wpcf7" => 3,
"_wpcf7_version" => "4.9.2",
"_wpcf7_locale" => "en_US",
"_wpcf7_unit_tag" => "wpcf7-f3-p2-o1",
"_wpcf7_container_post" => 2,
"your-name" => "sad",
"your-subject" => "sad",
"your-message" => "sdsa"];

$keys = array_keys($arr);
$count = count($keys)-1;
$namearr=[];
for($i = $count; $i >$count-3;$i-- ){
    $namearr[$keys[$i]] = $arr[$keys[$i]];
}
var_dump($namearr);

输出:

array(3) {
  "your-message" => "sdsa"
  "your-subject" => "sad"
  "your-name" => "sad"
}

https://3v4l.org/L9Cmp

答案 3 :(得分:0)

简单易行: - “从_wpcf7开始删除密钥并将其余密钥存储在另一个数组中”

<?php
    $oldArray = array(('_wpcf7') => '3',
        ('_wpcf7_version') => '4.9.2',
        ('_wpcf7_locale') => 'en_US',
        ('_wpcf7_unit_tag') => 'wpcf7-f3-p2-o1',
        ('_wpcf7_container_post') => '2',
        ('your-name') => 'sad',
        ('your-subject') => 'sad',
        ('your-message') => 'sdsa');
    $newArray = array();
    foreach($oldArray as $key => $value) {
        if (substr($key,0,6) !== '_wpcf7')
            $newArray[$key] = $value;
    }
?>

同时检查此代码: - Fiddle
快乐编码: - )