nudodudeda
nudodudeda

Reputation: 13

Parse array to change $key and add new $value => $key

I have such array:

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"
    ]

I need to get this:

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"
    ]

I try parse array ($key => $value). When $value == rt_field: I try rename $key to $key.'_txt', and add such key as default (without _txt) with $value = rt_attr_string.

My code:

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;

But $key in first array doesn't edit.

What I do wrong?

Upvotes: 1

Views: 69

Answers (2)

Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

Here is your solution....

Your Array

$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"
);

Solution

$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);

Upvotes: 0

Jerodev
Jerodev

Reputation: 33186

You are editing the value in either array. If you want to update a key, you need to create a new key.

You can just add the keys to a new array, this way there is no need for merging after the 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;
    }
}

Upvotes: 1

Related Questions