English 中文(简体)
更改json关键名称 [json 采用json_encode生成]
原标题:change json key name [ json generated using json_encode ]
  • 时间:2011-05-06 22:06:57
  •  标签:
  • php
  • json

我正在利用<代码>json_encode(>>)从一个阵列中生成json,该阵列运转正常,但使用钥匙:按惯例从阵列中的价值。 但是,我只想改变json产出中的关键名称。 这样做是可能的? 或者,我是否准备了json的钥匙:人工估价?

例:

$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}

我想。

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

编辑: 我不能篡改原来的阵列。

最佳回答

只有当你重写时。 您可以使用:

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

不知道这符合你的目标。

问题回答

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.

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  / .$k. /u ; }, array_keys($mapping_array));

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

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 ],
    ];
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签