1

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?

1
  • second array length is 10 not 8 Commented Dec 11, 2017 at 9:33

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if this is multidimensional array...?
That was not the question.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.