6

I am generating json from an array using json_encode(), it's working properly, but it uses the key:value from the array, as usual. but I want to change the name of the key only in the json output.. is it possible to do it ? or should I prepare the json key:values myself manually ?

Example:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);

O/P

{"a":1,"b":2,"c":3,"d":4,"e":5}

I want .

{"foo":1,"something":2,"bar":3,"foo":4,"baz":5}

edit : I cannot edit the original array..( generated using framweork)

3
  • where do the foo something bar keys come from? Commented May 6, 2011 at 22:09
  • if you can't edit the original array, just create a new one using the original's values, then convert that to json. Commented May 6, 2011 at 22:10
  • it will be common for every task . I want name: , type: , size: ..and it wont change.. -- thanks ! Commented May 6, 2011 at 22:11

4 Answers 4

7

Only if you rewrite 'm yourself. You could use:

$rewriteKeys = array('a' => 'foo', 'b' => 'something', 'c' => 'bar', 'd' => 'foo', 'e' => 'baz');

$newArr = array();
foreach($arr as $key => $value) {
  $newArr[ $rewriteKeys[ $key ] ] = $value;
}

echo json_encode($newArr);

Not sure if that's what you were aiming for.

Sign up to request clarification or add additional context in comments.

Comments

0

You can always json_decode it and then re-encode it. But it's going to be easiest if you simply prepare your keys before you encode it.

Comments

0

There is another option I described here. The main idea is to consider JSON as a string and then use str_replace or preg_replace(str_replace for regexp).

There is a code for your case.

$mapping_array  = array('a' => 'foo', 'b' => 'something', 'c' => 'bar', 'd' => 'foo', 'e' => 'baz');

$tmp_arr =  array_map(function($k){ return '/\b'.$k.'\b/u'; }, array_keys($mapping_array));

$new_json =  preg_replace($tmp_arr, array_values($mapping_array), $old_json);

Comments

0

This may be a short answer:

foreach ($list as $key => $val) {
    $newList[$key] = [
        'foo'   =>  $val['a'],
        'something' =>    $val['b'],
        'bar' => $val['c'],
        'foo' => $val['d'],
        'baz' => $val['e'],
    ];
}

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.