Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
620 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...