解析数组以更改$ key并添加新的$ value => $关键

时间:2017-12-11 09:27:48

标签: php arrays laravel laravel-5 php-7

我有这样的阵列:

array:8 [
      "text" => "rt_field"
      "title" => "rt_field"
      "type_id" => "rt_attr_uint"
      "author_id" => "rt_attr_uint"
      "created_at" => "rt_attr_timestamp"
      "recommended_at" => "rt_attr_timestamp"
      "deleted_at" => "rt_attr_timestamp"
      "feeds" => "rt_attr_multi"
    ]

我需要得到这个:

array:10 [
      "text" => "rt_attr_string"
      "text_txt" => "rt_field"
      "title" => "rt_attr_string"
      "title_txt" => "rt_field"
      "type_id" => "rt_attr_uint"
      "author_id" => "rt_attr_uint"
      "created_at" => "rt_attr_timestamp"
      "recommended_at" => "rt_attr_timestamp"
      "deleted_at" => "rt_attr_timestamp"
      "feeds" => "rt_attr_multi"
    ]

我尝试解析数组($key => $value)。 $value == rt_field时:我尝试将$key重命名为$key.'_txt',并将此键作为默认值(不_txt}添加$value = rt_attr_string

我的代码:

foreach ($array_param as $key => $value) {
    if ($value == 'rt_field'){
        $array_param_second[$key] = 'rt_attr_string';
        $array_param[$key] = $key.'_txt';
    }
}

$result = array_merge($array_param, $array_param_second);

return $result;

但是第一个数组中的$key不会编辑。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您正在编辑任一数组中的值。如果要更新密钥,则需要创建新密钥。

您可以将键添加到新数组中,这样就不需要在foreach之后进行合并。

$result = [];
foreach ($array_param as $key => $value) {
    if ($value == 'rt_field'){
        $result[$key] = 'rt_attr_string';
        $result[$key . '_txt'] = $value;
    } else {
        $result[$key] = $value;
    }
}

答案 1 :(得分:0)

这是你的解决方案......

您的数组

$array[] = array(
    "text" => "rt_field",
    "title" => "rt_field",
    "type_id" => "rt_attr_uint",
    "author_id" => "rt_attr_uint",
    "created_at" => "rt_attr_timestamp",
    "recommended_at" => "rt_attr_timestamp",
    "deleted_at" => "rt_attr_timestamp",
    "feeds" => "rt_attr_multi"
);

解决方案

$new = array();
$keys = array_keys($array[0]);
foreach($array as $r){
    for($i=0;$i<count($keys);$i++){
        $key = $keys[$i];
        if($r[$key]=='rt_field'){
            $new[$key.'_txt'] = $r[$key];
            $new[$key] = 'rt_attr_string';
        }
        else $new[$i][$key] = $r[$key];
    }
}
echo "<pre>";print_r($new);