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)
Related
Assuming I have two arrays:
$a = ['a', 'b' => array('Jack', 'John'), 'c'];
$b = ['1', '2', '3'];
How can I push $b to be "under" the value 'Jack' in $a, to make it a multidimensional array? So, the end result should look like this:
$ab = ['a', 'b' => ['Jack' => ['1', '2', '3'], 'John'], 'c'];
I understand that this changes the value of $a[1]['Jack'] = 'b' to become a key, but that's fine with me.
How can I do this?
You can recursively iterate through the array with a function until you get the right value ('Jack') like this:
function iterateArr (&$array) {
if (is_array($array)) {
foreach ($array as $key => &$val) {
if (is_array($val)) {
iterateArr($val);
} elseif ($val == 'Jack') {
global $b;
unset($array[$key]);
$array[$val] = $b;
}
}
}
}
iterateArr($a);
For your example, this'd output:
['a', 'b' => ['John', 'Jack' => ['1', '2', '3']], 'c']
eval.in demo
But the beauty of this is that it'll work no matter how many levels deep your array is, since it's a recursive iterator. e.g., for an array like:
['a', 'b' => ['1', '2', '3' => ['i' => ['Jack', 'John'], 'ii', 'ii', 'iv', 'v']], 'c']
The output'd be:
['a', 'b' => ['1', '2', '3' => ['i' => ['John', 'Jack' => ['1', '2', '3']], 'ii', 'ii', 'iv', 'v']], 'c']
eval.in demo
$a = ['a', 'b' => array('Jack', 'John'), 'c'];
$b = ['1', '2', '3'];
unset($a['b'][0]); // go inside array $a and get the first value (B in
// this case)
// Then get the key you wanna change.
// Remove that value so we can 'reset' it.
$a['b'][0] = $b; // set array $b as that value;
Given this array:
$list = array(
'one' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
'two' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
'three' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
'four' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
),
'five' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
);
I need a function(replaceKey($array, $oldKey, $newKey)) to replace any key 'one', 'two', 'three', 'four' or 'five' with a new key independently of the depth of that key. I need the function to return a new array, with the same order and structure.
I already tried working with answers from this questions but I can't find a way to keep the order and access the second level in the array:
Changing keys using array_map on multidimensional arrays using PHP
Change array key without changing order
PHP rename array keys in multidimensional array
This is my attempt that doesn't work:
function replaceKey($array, $newKey, $oldKey){
foreach ($array as $key => $value){
if (is_array($value))
$array[$key] = replaceKey($value,$newKey,$oldKey);
else {
$array[$oldKey] = $array[$newKey];
}
}
return $array;
}
Regards
This function should replace all instances of $oldKey with $newKey.
function replaceKey($subject, $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($subject)) return $subject;
$newArray = array(); // empty array to hold copy of subject
foreach ($subject 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
$newArray[$key] = replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}
I need a custom array_replace_recursive($array, $array1) method which does what the original array_replace_recursive($array, $array1) method does except that for indexed array it should use the array in the second array and overwrite the first array recursively.
example:
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3)
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3)
);
$c = array_replace_recursive($a, $b);
current behaviour:
$c = array (
'a' => array(4,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
desired behaviour:
$c = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
as you can see element 'a' is an indexed array so the element in the second array has overwritten the element in the first array. element 'b' is an associative array so it maintains the original behaviour.
Below worked for me:
<?php
/**
* This method finds all the index arrays in array2 and replaces array in array1. it checks for indexed arrays recursively only within associative arrays.
* #param $array1
* #param $array2
*/
function customMerge(&$array1, &$array2) {
foreach ($array2 as $key => $val) {
if(is_array($val)) {
if(!isAssoc($val)) {
if($array1[$key] != $val) {
$array1[$key] = $val;
}
} else {
$array1_ = &$array1[$key];
$array2_ = &$array2[$key];
customMerge($array1_, $array2_);
}
}
}
}
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'g' => array(
4,5,6
))
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3, 'g' => array(
7
))
);
$c = array_replace_recursive($a, $b); // first apply the original method
$expected = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3, 'g'=> array(
7
)),
);
$d = $c; // create copy
customMerge($d, $b); // do the custom merge
echo $d == $expected;
The isAssoc() method in the first answer of this post is what your looking for:
How to check if PHP array is associative or sequential?
That method will check if the array is index and return true if it's the case.
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()
How can I group same values in a multidimention array?
I want this
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world'),
array('a' => 2, 'b' => 'you')
)
to become
array(
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world')
),
array('a' => 2, 'b' => 'you')
)
function array_gather(array $orig, $equality) {
$result = array();
foreach ($orig as $elem) {
foreach ($result as &$relem) {
if ($equality($elem, reset($relem))) {
$relem[] = $elem;
continue 2;
}
}
$result[] = array($elem);
}
return $result;
}
then
array_gather($arr,
function ($a, $b) { return $a['a'] == $b['a']; }
);
This could be implemented in a more efficient matter if all your groups could be reduced to a string value (in this case they can, but if your inner arrays were something like array('a' => ArbitraryObject) they could not be).