-1

I want to convert this array where id as key and name value pair

Array(
    [4882] => treatment
    [4876] => Advance
    [4854] => Applied Clinical
)

to

Array(
    [0] => Array([id] => 4882, [name] => treatment)
    [1] => Array([id] => 4876, [name] => Advance)
    [2] => Array([id] => 4854, [name] => Applied Clinical)
)
0

4 Answers 4

3
foreach ($original_array as $key=>$value){
    $new_arrays[] = array('id'=>$key,'name'=>$value);
}

print_r($new_arrays);
Sign up to request clarification or add additional context in comments.

Comments

2

You can do so:

$output_arr = array();
foreach($input_arr as $key => $value)
  $output_arr[] = array('id' => $key, 'name' => $value);

And then you can use $output_arr as converted array or assign its contents to $input_arr:

$input_arr = &$output_arr;

Comments

2

$input is your first array, $output will hold the resulting array

$output = array();
foreach ($input as $id => $name)
{
  $output[] = array('id'=>$id, 'name'=>$name);
}

Comments

-1

Here are some more working solutions that endeavour to craft concise code.

Functional programming with parameter-derived associative keys Demo

var_export(
    array_map(
        fn(int $id, string $name) => get_defined_vars(),
        array_keys($array),
        $array
    )
);

Classic loop with associative keys born from foreach loop variable names Demo

$result = [];
foreach ($array as $id => $name) {
    $result[] = compact(['id', 'name']);
}
var_export($result);

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.