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/
Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';
I have this json array in json file
[["a","b","c","d"],["3","2","25","25"],["4","48","20","20"],["3","1","22","22"],["5","4","31","31"],["5","3","33","33"],["5","6","43","43"],["5","8","45","45"],["5","5","42","42"],["5","11","37","37"],["5","7","40","40"],["5","10","36","36"],["1","35","40","40"],["2","22","38","38"],["2","23","35","35"],["1","31","34","34"],["2","19","43","43"],["2","17","35","35"],["3","14","20","20"],["3","15","17","17"],["3","13","16","16"],["2","20","36","36"],["1","39","28","28"],["3","26","20","20"],["4","46","20","20"],["1","36","32","32"],["1","37","21","21"],["3","9","5","5"],["3","12","23","23"],["3","18","21","21"],["3","16","22","22"],["3","21","15","15"],["4","34","6","6"],["1","33","29","29"],["1","32","24","24"],["1","30","30","30"],["3","24","27","27"],["3","27","23","23"],["3","25","23","23"],["3","28","6","6"],["3","29","18","18"],["4","47","19","19"],["4","51","6","6"],["4","50","4","4"],["1","49","26","26"],["1","40","41","41"],["1","41","43","43"],["4","43","2","2"],["4","44","1","1"],["1","38","44","44"],["1","45","37","37"],["1","42","39","39"],["4","61","3","3"],["4","60","7","7"],["4","57","10","10"],["4","58","14","14"],["4","56","8","8"],["4","54","12","12"],["4","59","9","9"],["4","55","10","10"],["4","53","11","11"],["4","52","13","13"]]
I need to add another array to the above json array,
that is
[["e"],["45"
],["37"],["40"],["57"],["61"],["85"],["96"],["79"],["71"],["77"],["68"],["77"],["73"],["65"],["64"],
["85"],["65"],["37"],["31"],["30"],["68"],["49"],["37"],["37"],["60"],["39"],["21"],["42"],["39"],["40"
],["28"],["22"],["51"],["43"],["55"],["48"],["42"],["42"],["22"],["34"],["35"],["22"],["18"],["47"],
["78"],["85"],["104"],["100"],["92"],["71"],["74"],["140"],["222"],["248"],["276"],["229"],["259"],["233"
],["248"],["250"],["268"]]
I need the output like this in Array
[["a,b,c,d,e"],["3","2","25","25","45"]]
I'm not able to do it in array_push, array_merge. Can any help me ?
Thanks in advance ...
You should have get the json string in a php variable. then:
$array1 = json_decode($json_string1, true);// not needed if already you have an array
$array2 = json_decode($json_string2, true);
$merged = array();
foreach( $array1 as $key => $value ){
if(array_key_exists($key, $array2)){
$merged[] = array_merge($value, $array2[$key]);
}else{
$merged[] = $value ;
}
}
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)
I have an associative array in PHP
$a = array("d1" => "data", "d2" => NULL, "d3" => "data")
I want to get all keys and all values which are not NULL, in order to implode them:
// e.g.:
$sub_key = array_keys($a, keys != NULL);
$sub_values = array_values($a, values != NULL);
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'";
Are there functions like array_keys() and array_values() that allow to take only vales that do not match the pattern?
Use array_filter before using array_keys and filter the array like this
$newArray = array_filter($a);
Then do
$sub_key = array_keys($newArray);
$sub_values = array_values($newArray);
You could use array_filter($a), but as one of the comments above pointed out, this would also filter out values like FALSE, empty strings, etc. So I'd use a foreach loop.
$new_array = array();
foreach ($a as $key => $value) {
if (is_null($value) === false) {
$new_array[$key] = $value;
}
}
Please try this:
// Loop to find empty elements and
// unset the empty elements
foreach($array as $key => $value)
if(empty($value))
unset($array[$key]);
// Display the array elements
foreach($array as $key => $value)
echo ($array[$key] . "<br>");
In you case you will replace $array with $a. This will work for null/empty key values.
$a = array("d1" => "data1", "d2" => NULL, "d3" => "data3");
$b = array_filter($a); // Not Null Values Array
$sub_key = array_keys(array_filter($a));
$sub_values = array_values(array_filter($a));
echo "`".implode("`,`", $sub_key)."` <br/>";
echo "'".implode("','", $sub_values)."'";
$sub_key = array();
$sub_values = array();
foreach ($a as $key => $value) {
if (!is_null($key) && !is_null($value)) { // you can also do is_empty() in stead of is_null() if you also wan't to avoid empty string
$sub_key[] = $key;
$sub_values[] = $value; // or use mysql_real_escape_string($value) if you are going to create a query with this! Otherwise you will create an SQL injection vulnerability here.
}
}
// you can add if(count($sub_key)) here to only do the echoes, if there was at least 1 item in the array. Otherwise you will echo an empty ``
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'"; // don't you mean $sub_values here?