I would like to make an array of arrays with keys associated, and I don't really know what is the proper way to do it.
For example if I have
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
$array2 = array(
"foo2" => "bar2",
"bar2" => "foo2",
);
Would it be correct to write:
$key_array=array("first"=>$array1,
"second"=>$array2);
And, if not, how should I do this?
Thanks in advance
your code is correct, in fact you could also do:
$key_array = array(
'first' => array('first' => $array1, 'second' => $array2),
'second' => array('first' => $arra1, 'second' => $array2)
);
and nest it as deep as you want.
Related
I have an array like this:
[
'one' => ['whatever'=>'something','whatever1'=>'something1'],
'two' => ['whatever'=>'something','whatever1'=>'something1'],
'three' => ['whatever'=>'something','whatever1'=>'something1'],
]
and now I wanna add the array keys to the same array with a specific key like below:
[
'one' => ['name'=>'one', 'whatever'=>'something','whatever1'=>'something1'],
'two' => ['name'=>'two', 'whatever'=>'something','whatever1'=>'something1'],
'three' => ['name'=>'three', 'whatever'=>'something','whatever1'=>'something1'],
]
I can handle this with foreach() but is there no function in PHP that can do this or in a shorter way?
Yes there is are lot of functions for array handling, if you are the starter then you have to do with foreach.
If you have an array named $array , then you can try this-
$array = array_map(function (array $arr, $arr_key) { return $arr + array('name' => $arr_key); }, $array, array_keys($array));
My multidimensional arrays are
$input_array = array(
array(
'First' => 1,
'Third' => 3
),
'Second' => 2,
'Fourth' => 4
);
$another_array = array(
'First' => array(
'Third' => 3,
'Fifth' => 5
),
'Second' => 2,
'Fourth' => 4
);
How can I change the key case of these two multidimensional arrays using array_change_key_case() in PHP?
Find answer here http://php.net/manual/en/function.array-change-key-case.php#114914
function array_change_key_case_recursive($arr)
{
return array_map(function($item){
if(is_array($item))
$item = array_change_key_case_recursive($item);
return $item;
},array_change_key_case($arr));
}
$input_array = array(array('First'=>1,'Third'=>3),'Second'=>2,'Fourth'=>4);
return array_change_key_case_recursive($input_array);
Try demo https://implode.io/LCW5CG
I have this array :
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
And I would like to obtain this one :
array(
'AMO' => array(),
'PAT' => array()
)
How could I do this, in the shortest way possible ?
I can do it with an array_map, followed by an array_flip and next an array_walk .. but too long.
array_column to extract the keys and array_fill_keys to create the new array:
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
$res = array_fill_keys(array_column($arr, 'id'), []);
simply loop over array and make its id to new array key
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
foreach($arr as $value)
{
$new_arr[$value['id']] = array();
}
print_r($new_arr);
DEMO
I dont know what is the logic behind this, but you can try this one.
Here we are using array_combine, array_keys and array_fill
Try this code snippet here
$result= array_combine(
array_column($array,"id"),//getting column id
array_fill(0, count($array), array())//mapping that keys with empty array
);
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)))!
Assume I have the following array:
$array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
)
I am only interested in the first $array item:
$array2 = array('key'=> 32, 'name' => 'paul', 'age' => 43)
What is the most efficient way to accomplish this? In other words, can I throw out all other items of $array with one command?
Use array_shift().
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be touched.
$array2 = array_shift($array);
This means that $array2 now holds the first element, while $array holds the rest of the elements.
try this
$array2 = array_shift($array);
$newArr = reset($array);
I think there is no problem with that.
There are 2 options, really. Either you can just select the first item in the array
$array2 = $array[0];
Or you could use array_slice as
$array2 = array_slice($array, 0, 1);
Array_shift is probably the best way. But just for fun here is another way.
$first_element = end(array_reverse($array));
$k = array_merge(array('key' => key($array)), array_shift($array));
Returns in the specified format.
key gets you the first key, array_shift gets you the first value, and merge using array_merge
resetting an array also returns the first element (end() returns the last):
$first = reset( $array );
http://www.php.net/manual/en/function.reset.php
But to generate the exact result you want, you could write something like this
foreach( $array as $k => $first ){ // get first sub-array and its key
$first['key'] = $k; // add the key
break; // we don't care about the other elements, goodbye
}
Futuregeek's method fixed:
$first =
// returns first element, and sets it as the current element for key()
reset( $array )
// instead of array_merge, (sometimes) you can use the + operator
+
// key() will return the appropriate key after reset()
array('key' => key( $array ));
Try It :
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
foreach($arr as $key => $value)
{
$result[$key] = $value;
break;
}
print_r($result);
##-------Secount Way If you don't want Key 32--------------------------
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$arr = array_reverse($arr);
print_r(end($arr));
#------ Third Way If you don't want Key 32 -------------
echo "<br>=======<br>";
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$array2 = array_shift($arr);
print_r($array2);