I have a MYSQL query that fetches an array of dictionaries or results which are returned via JSON in an api. In some cases, I would like to change the name of the dictionary keys in the results array.
For example, in the following case:
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
I would like to change it to:
$var = '[{"golfer":"Tiger Woods"},{"golfer":"Gary Player"}]'
It is not practical in this case to change the mysql query so I'd just like to replace the word "player" with the word "golfer" for the keys without disturbing the values.
In the above example, I would not want to change Gary Player's name so just using str_replace does not seem like it would work.
Is there a way to change all of the keys from "player" to "golfer" without changing any of the values?
Here is the snippet you can use
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
// json decode the json string
$temp = json_decode($var, true);
$temp = array_map(function($item){
// combining key and values
return array_combine(['golfer'], $item);
}, $temp);
print_r($temp);
// or echo json_encode($temp);
Demo.
Some argue that foreach is fastest,
foreach($temp as $k => &$v){
$v = array_combine(['golfer'], $v);
}
print_r($temp);
Demo.
Little hardcoded if more than one keys in single array,
foreach ($temp as $k => &$v){
$v['golfer'] = $v['player'];
unset($v['player']);
}
print_r($temp);
Demo.
Using recursion
function custom($arr, $newKey, $oldKey)
{
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($arr)) {
return $arr;
}
$result = []; // empty array to hold copy of subject
foreach ($arr as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$result[$key] = custom($value, $newKey, $oldKey);
}
return $result;
}
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$temp = json_decode($var, true);
$temp = replaceKey($temp, 'golfer', 'player');
print_r($temp);
Demo & source.
Using json way,
function json_change_key($arr, $oldkey, $newkey) {
$json = str_replace('"'.$oldkey.'":', '"'.$newkey.'":', json_encode($arr));
return json_decode($json, true);
}
$temp = json_change_key($temp, 'player', 'golfer');
print_r($temp);
Demo
If you want multiple key replace, here is the trick,
$var = '[{"player":"Tiger Woods", "wins":"10","losses":"3"},{"player":"Gary Player","wins":"7", "losses":6}]';
$temp = json_decode($var, true);
function recursive_change_key($arr, $set)
{
if (is_array($arr) && is_array($set)) {
$newArr = [];
foreach ($arr as $k => $v) {
$key = array_key_exists($k, $set) ? $set[$k] : $k;
$newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;
}
return $newArr;
}
return $arr;
}
$set = [
"player" => "golfers",
"wins" => "victories",
"losses" => "defeats"
];
$temp = recursive_change_key($temp, $set);
print_r($temp);
Demo.
$a = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$array = json_decode($a, true);
foreach($array as $key=>$value){
if(array_keys($value)[0] === "player"){
$array[$key] = ["golfer" => array_values($value)[0]];
};
}
echo json_encode($array);
you can write the value of the key to a new key and then delete the old.
renaming a key called "a" to "b", while keeping the value.
var json = {
"a" : "one"
}
json["b"] = json["a"];
delete json["a"];
for your example, just use this with a loop.
source: https://sciter.com/forums/topic/how-to-rename-the-key-of-json/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this json held in a variable that I am trying to convert to a string?
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
What I want as my end result is something that looks like this:
$json_object1 = '1,2,3,4,5,6,7,8,9,10,11';
$json_object2 = '125,126,127,128,129,130,131,132,133,134,135';
Is there a way we can modify the implode(",",$json_object) function to achieve this?
Another question:
Any idea how we might put this
{"26":"Child - 1500.00","28":"Foreigner - 4000.00","27":"Resident - 3000.00"}
To a list like
26 : Child - 1500.00
27: Resident - 3000.00
28: Foreigner - 4000.00
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$json = json_decode($json_object);
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $p;} }, $json));
echo "<br>";
echo implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $v;} }, $json));
See https://3v4l.org/p3p45
Try this:
<?php
$jsonString = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$decoded = json_decode($jsonString, true);
$keys = [];
$values = [];
foreach($decoded as $item) {
foreach($item as $key => $value) {
$keys[] = $key;
$values[] = $value;
}
}
$resultStringKeys = implode(",", $keys);
$resultStringValues = implode(",", $values);
var_dump($resultStringKeys, $resultStringValues);
The output:
string(43) "125,126,127,128,129,130,131,132,133,134,135"
string(23) "1,2,3,4,5,6,7,8,9,10,11"
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$arr1 = []; $arr2=[];
$jsonobj = json_decode($json_object);
foreach ($jsonobj as $val){
$Arrval = (array) $val;
foreach ($Arrval as $k=>$v){
$arr1[]=$k;
$arr2[]=$v;
}
}
$json_object1 = implode(",",$arr1);
$json_object2 = implode(",",$arr2);
Out put is
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11
Another possible solution (not the best if the size of your JSON input is measured in MBs but good enough for several KBs of input):
$input = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
// Decode the JSON into arrays; TRUE as the second argument requires arrays, not objects
$data = json_decode($input, TRUE);
// Run through the list, extract the data into a new list
$output = array_reduce(
$data,
function(array $carry, array $item) {
// Put the keys and values of $item into the corresponding lists on $carry
$carry['keys'] = array_merge($carry['keys'], array_keys($item));
$carry['vals'] = array_merge($carry['vals'], array_values($item));
return $carry;
},
// Start with empty lists of keys and values
array('keys' => array(), 'vals' => array())
);
// That's all; $output['keys'] contains the keys, $output['values'] contains the values.
echo('Keys: '. implode(',', $output['keys'])."\n");
echo('Values: '.implode(',', $output['vals'])."\n");
You can achieve like this,
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$key_arr = array();
$val_arr = array();
$json_arr = json_decode($json_object);
foreach($json_arr as $val)
{
foreach($val as $key => $value)
{
$key_arr[] = $key;
$val_arr[] = $value;
}
}
$resultStringKeys = implode(",", $key_arr);
$resultStringValues = implode(",", $val_arr);
And echo your $resultStringKeys and $resultStringValues and you will get your output.
first convert json data to php array then store all key and value in different array then implode it
<?php
$json_object = '[{"125":"1"},{"126":"2"},{"127":"3"},{"128":"4"},{"129":"5"},{"130":"6"},{"131":"7"},{"132":"8"},{"133":"9"},{"134":"10"},{"135":"11"}]';
$array_data = json_decode($json_object, true);
foreach($array_data as $data) {
foreach($data as $key => $value) {
$array_key[] = $key;
$array_value[] = $value;
}
}
$final_key = implode(",", $array_key);
$final_value = implode(",", $array_value);
echo $final_key;
echo "<br>";
echo $final_value;
then output is :
125,126,127,128,129,130,131,132,133,134,135
1,2,3,4,5,6,7,8,9,10,11
I have a JSON string in this variable:
$value = $request->pre_departure_type;
With the value:
"30":0 ,"31":2
I want to get the values 30 and 0, 31 and 2 from the above JSON string.
I tried this code:
$result = array();
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
But this didn't explode the string on the double quotes.
If You are getting the perfect answer from your code then i think there is a problem because of double inverted comma. firstly remove it.
$str = str_replace('"', '', $value);
You will get value like below
value = 30:0 ,31:2
after that you will convert it in to array.
First replace double quotes and then do the same process as you did.
$result = array();
$newvalue = str_replace('"', '', $value);
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
If you are getting your desired result but with quotations then simply use this function to remove quotations:
$str = str_replace('"', '', $string_to_replace);
your value coming as a json format so first you need to convert it to object and then array and do manipulation as follow
$valueArr=(array)json_decode($value);
$finalArray=array();
foreach($valueArr as $k=>$v){
array_push($finalArray,$k);
array_push($finalArray,$v);
}
echo "<pre>";print_r($finalArray);
$value = '{"30":0 ,"31":2}'; // this is a json
$data = json_decode($value); // json to object
foreach($data as $key=>$value)
{
echo $key; // get key
echo $value; //get value
}
get values 30 and 0 , 31 and 2 from above
I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}