Bolt
Bolt

Reputation: 23

Prepend character to key in PHP array

I am trying to convert a data source (Array ( [0] => [1] => [2] => 1 [3] =>...) to use in json. In my php page, I use json_encode((object) $data) (also works as json_encode($data, JSON_FORCE_OBJECT)) which yields an array that looks like: {"0":false,"1":false,"2":true,"3":false,...}. I would like to add a character in front of the key, returning as {"A0":false,"A1":false,"A2":true,"A3":false,...}. How do I go about doing so?
I have searched this forum and google extensively but am having no luck. How do I prepend or concatenate a character to the key?

Upvotes: 2

Views: 161

Answers (3)

Dan
Dan

Reputation: 11104

If you are working in PHP, then I would suggest to do any manipulation in PHP before json_encodeing.

Say your array is called $arr:

//Make array of new keys
$newKeys = array_map(function($k){return 'A'.$k;}, array_keys($arr));
//Combine new keys with value
$newArray = array_combine($newKeys, $arr);

Upvotes: 2

poplitea
poplitea

Reputation: 3737

You could replace the array keys like this:

foreach ($data  as $key=>$value)
{
    $data["A".$key] = $value;
    unset($data[$key]);
}

Upvotes: 0

This should work:

<?php
$source = [0 => 'bla', 1 => 'blop'];

// Get your keys
$keys = array_keys($source);

// Prepend whatever to each key
$formatted_keys = array_map(function ($key) {
    return 'A' . $key;
}, $keys);

// Build a new array using $formatted_keys for keys
// and array_values($source) for values.
$result = array_combine($formatted_keys, array_values($source));


http://php.net/manual/en/function.array-keys.php  
http://php.net/manual/en/function.array-values.php  
http://php.net/manual/en/function.array-combine.php  

Upvotes: 0

Related Questions