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)
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.
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 '/\b'.$k.'\b/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'],
];
}
Related
I have an array that I need to get a value from within the same array that is unassigned to a variable:
return ['a' => 1, 'b'=> 'a', 'c' => 2];
So in this case I need 'b' to return the same value as 'a'. Which would be 1
Thanks for the help.
edit
I intend on running a function on b's value so the value of b is slightly different than a
return ['a' => 1, 'b'=> myFunction('a'), 'c' => 2];
You can try this way.
foreach ($array as $key => $agent) {
$array[$key]['agent_address_1'] = $agent['agent_company_1'] . ', ' .$agent['agent_address_1'];
unset($array[$key]['agent_company_1']);
}
What you want is not clear.
But i am assuming that you are trying to get the 'b' element of an array to be assigned a value similar to the value of 'a' element of that same array
If that is what you need, this will do it.
<?php
$a = array('a' => 1, 'b' => null, 'c' => 2);
$a['b'] = myFunction($a, 'a');
function myFunction($a, $b)
{
return $a[$b];
}
var_dump($a);
You can then return the array, or do what you want with it.
Maybe something like
<?php
function resolve(array $arr) {
foreach($arr as &$v) {
if ( isset($arr[$v])) {
$v = $arr[$v];
}
}
return $arr;
}
function foo() {
return resolve( ['a' => '5', 'b'=>'a', 'c' => '1'] );
}
var_export( foo() );
will do, prints
array (
'a' => '5',
'b' => '5',
'c' => '1',
)
But keep in mind that resolve( ['b'=>'a', 'a' => 'c', 'c' => '1'] ); will return
array (
'b' => 'c',
'a' => '1',
'c' => '1',
)
(you could resolve that with while( isset($arr[$v])) { instead of if ( isset($arr[$v]) ) { ...but there are most likely more elegant/performant ways to do that)
How can I split a single array into it's sub-keys?
$arr = array(
0 => array(
'foo' => '1',
'bar' => 'A'
),
1 => array(
'foo' => '2',
'bar' => 'B'
),
2 => array(
'foo' => '3',
'bar' => 'C'
)
);
What is the most efficient way to return an array of foo and bar separately?
I need to get here:
$foo = array('1','2','3');
$bar = array('A','B','C');
I'm hoping there's a clever way to do this using array_map or something similar. Any ideas?
Or do I have to loop through and build each array that way? Something like:
foreach ($arr as $v) {
$foo[] = $v['foo'];
$bar[] = $v['bar'];
}
In a lucky coincidence, I needed to do almost the exact same thing earlier today. You can use array_map() in combination with array_shift():
$foo = array_map('array_shift', &$arr);
$bar = array_map('array_shift', &$arr);
Note that $arr is passed by reference! If you don't do that, then each time it would return the contents of $arr[<index>]['foo']. However, again because of the reference - you won't be able to reuse $arr, so if you need to do that - copy it first.
The downside is that your array keys need to be ordered in the same way as in your example, because array_shift() doesn't actually know what the key is. It will NOT work on the following array:
$arr = array(
0 => array(
'foo' => '1',
'bar' => 'A'
),
1 => array(
'bar' => 'B',
'foo' => '2'
),
2 => array(
'foo' => '3',
'bar' => 'C'
)
);
Update:
After reading the comments, it became evident that my solution triggers E_DEPRECATED warnings for call-time-pass-by-reference. Here's the suggested (and accepted as an answer) alternative by #Baba, which takes advantage of the two needed keys being the first and last elements of the second-dimension arrays:
$foo = array_map('array_shift', $arr);
$bar = array_map('array_pop', $arr);
$n = array();
foreach($arr as $key=>$val) {
foreach($val as $k=>$v) {
$n[$k][] = $v;
}
}
array_merge_recursive will combine scalar values with the same key into an array. e.g.:
array_merge_recursive(array('a',1), array('b',2)) === array(array('a','b'),array(1,2));
You can use this property to simply apply array_merge_recursive over each array in your array as a separate argument:
call_user_func_array('array_merge_recursive', $arr);
You will get this result:
array (
'foo' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'bar' =>
array (
0 => 'A',
1 => 'B',
2 => 'C',
),
)
It won't even be confused by keys in different order.
However, every merged value must be scalar! Arrays will be merged instead of added as a sub-array:
array_merge_recursive(array(1), array(array(2)) === array(array(1,2))
It does not produce array(array(1, array(2)))!
I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same order as the first array.
Is there a function that can quickly do this?
I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?
$arr1 = array(
'a' => '42',
'b' => '551',
'c' => '512',
'd' => 'gge',
) ;
$arr2 = array(
'd' => 'ordered',
'b' => 'is',
'c' => 'now',
'a' => 'this',
) ;
$arr2ordered = array() ;
foreach (array_keys($arr1) as $key) {
$arr2ordered[$key] = $arr2[$key] ;
}
You can use array_replace
$arr1 = [
'x' => '42',
'y' => '551',
'a' => '512',
'b' => 'gge',
];
$arr2 = [
'a' => 'ordered',
'x' => 'this',
'y' => 'is',
'b' => 'now',
];
$arr2 = array_replace($arr1, $arr2);
$arr2 is now
[
'x' => this,
'y' => is,
'a' => ordered,
'b' => now,
]
foreach(array_keys($array1) as $key)
{
$tempArray[$key] = $array2[$key];
}
$array2 = $tempArray;
I am not completely sure if this is what your after. anyways as long as the the array remains the same size, than this should work for you.
$gamey = array ("wow" => "World of Warcraft", "gw2" => "Guild Wars2", "wiz101" => "Wizard 101");
$gamex = array ("gw2" => "best game", "wiz101" => "WTF?", "wow" => "World greatest");
function match_arrayKeys ($x, $y)
{
$keys = array_keys ($x);
$values = array_values ($y);
for ($x = 0; $x < count ($keys); $x++)
{
$newarray [$keys[$x]] = $y[$keys[$x]];
}
return $newarray;
}
print_r (match_arrayKeys ($gamey, $gamex));
Output
[wow] => World greatest
[gw2] => best game
[wiz101] => WTF?
Try this
CODE
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
OUTPUT
a = orange
b = banana
c = apple
d = lemon
Check the php manual for ksort()
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)
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.
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 '/\b'.$k.'\b/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'],
];
}
Imagine that I want to create an array from another array like this:
$array = array('bla' => $array2['bla'],
'bla2' => $array2['bla2'],
'foo' => $array2['foo'],
'Alternative Bar' => $array['bar'],
'bar' => $array2['bar']);
What is the best way to test either the $array2 has that index I'm passing to the other array, without using an if for each index I want to add.
Note that the key from the $array can be different from the $array2
What I did was, creating a template to the array with the keys that I want e.g.
$template = array('key1', 'key2', 'key3');
Then, I would merge the template with the other array, if any key was missing in the second array, then the value of the key would be null, this way I don't have the problem of warnings telling me about offset values.
$template = array('key1', 'key2', 'key3');
$array = array_merge($template, $otherarray);
if i understood right...
$a = array('foo' => 1, 'bar' => 2, 'baz' => 3);
$keys = array('foo', 'baz', 'quux');
$result = array_intersect_key($a, array_flip($keys));
this will pick only existing keys from $a
A possibility would be:
$array = array(
'bla' => (isset($array2['bla']) ? $array2['bla'] : ''),
'bla2' => (isset($array2['bla2']) ? $array2['bla2'] : ''),
'foo' => (isset($array2['foo']) ? $array2['foo'] : ''),
'xxx' => (isset($array2['yyy']) ? $array2['yyy'] : ''),
'bar' => (isset($array2['bar']) ? $array2['bar'] : '')
);
If this shoud happen more dynamically, I would suggest to use array_intersect_key, like soulmerge posted. But that approach would have the tradeoff that only arrays with the same keys can be used.
Since your keys in the 2 arrays can vary, you could build something half-dynamic using a mapping array to map the keys between the arrays. You have at least to list the keys that are different in your arrays.
//key = key in $a, value = key in $b
$map = array(
'fooBar' => 'bar'
);
$a = array(
'fooBar' => 0,
'bla' => 0,
'xyz' => 0
);
$b = array(
'bla' => 123,
'bar' => 321,
'xyz' => 'somevalue'
);
foreach($a as $k => $v) {
if(isset($map[$k]) && isset($b[$map[$k]])) {
$a[$k] = $b[$map[$k]];
} elseif(isset($b[$k])){
$a[$k] = $b[$k];
}
}
That way you have to only define the different keys in $map.
You want to extract certain keys from array1 and set non-existing keys to the empty string, if I understood you right. Do it this way:
# Added lots of newlines to improve readability
$array2 = array_intersect_key(
array(
'bla' => '',
'bla2' => '',
'foo' => '',
# ...
),
$array1
);
Perhaps this...
$array = array();
foreach ( $array2 as $key=>$val )
{
switch ( $key )
{
case 'bar':
$array['Alternative bar'] = $val;
break;
default:
$array[$key] = $val;
break;
}
}
For any of the "special" array indexes, use a case clause, otherwise just copy the value.