With a basic associative array like:
$ar = array("First" => 1, "Second" , "Third" =>"Three");
if you do:
foreach($ar as $key => $val) {
var_dump($key);
}
This will produce:
string 'First' (length=5)
int 0
string 'Third' (length=5)
How do you Achieve the same results in a Multidimensional Array?
Something like:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
I tried:
foreach($ar as $k => $v){
var_dump($ar[0][$k]);
}
I got:
string 'Two' (length=3)
Instead of:
string 'First' (length=5)
int 0
string 'Third' (length=5)
Thanx
function get_key(&$arr){
foreach($arr as $key=>$value){
if(is_array($value)){
get_key($value);
}else{
var_dump($key);
}
}
}
$arr = array(
'key1'=>array('a'=>1,'b'=>2),
'key2'=>array('c'=>1,2),
);
get_key($arr);
output:
string(1) "a"
string(1) "b"
string(1) "c"
int(0)
If $ar is equal to this:
array( 0 => array(
"First" => 1, "Two", "Third" => "Three"
)
);
You could iterate over the inner array to get the same result:
foreach ($ar as $k => $v) {
foreach ($v as $k2 => $v2) {
var_dump($k2);
}
}
Output:
string(5) "First"
int(0)
string(5) "Third"
You can iterate through the values of the inner array like this:
foreach($ar[0] as $k => $v){
var_dump($v);
}
The problem with yours is that you are only looping over 1 element in the ar array, and then applying that number to the array inside of it.
If you also want to do the same thing on both levels, you need another foreach loop like so:
foreach($ar as $k => $v){
foreach($v as $k => $n){
var_dump($n);
}
}
$arr = array(
0 => array("First" => 1, "Two", "Third" => "Three")
);
foreach ($arr as $key => $value)
{
foreach ($value as $k => $v)
{
var_dump($k);
}
}
You can access multidimensional Array keys and indexes like so:
$ary = array('whatever' => array('First' => 1, 'Two', 'Third' => 'Three'),
array('something' => array('cool' => 'yes', 'awesome' => 'super', 'great' => 10)
);
foreach($ary as $k => $a){
// $k is each Array key within initial Array
foreach($a as $i => $v){
// $i is internal index
// $v is internal value
}
}
Note:
In an Array that contains Arrays the first Array is really the value under key 0, unless the Array is assigned to a key, so your key, 0, is not necessary.
Related
Is there built-in function, or shorter way to extract elements into new array, as described here?
<?php
function arr_slice ($arr, $keys) {
$ret = array();
foreach ($keys as $k) { $ret[$k] = $arr[$k]; }
return $ret;
}
$array = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
var_export(
arr_slice($array, array("x","d","b"))
);
output (key order matters)
array (
'x' => NULL,
'd' => 4,
'b' => 2,
)
I have two arrays:
$arr1 = array("123" => "abc");
$arr2 = array("123" => "xyz", "456" => "lmn");
I want the resultant array to be:
$arr = array("123" => "abc,xyz", "456" => "lmn");
I know I can write some code to fetch the values corresponding to keys and then concat with a separator like ';' or ',', but I want to know is there any efficient way to do this?
An in-built function maybe?
Simple foreach will do! Check inline comments
$arr1 = ["123" => "abc"];
$arr2 = ["123" => "xyz", "456" => "lmn"];
foreach ($arr2 as $key => $value) {
if(array_key_exists($key, $arr1)) // Check if key exists in array
$arr1[$key] .= ",$value"; // If so, append
else
$arr1[$key] = $value; // otherwise, add
}
print_r($arr1);
Prints
Array
(
[123] => abc,xyz
[456] => lmn
)
Check this Eval
try this:
$arr1 = array("123" => "abc");
$arr2 = array("123" => "xyz", "456" => "lmn");
$o = [];
foreach($arr1 as $k => $v)
{
$o[$k][] = $v;
}
foreach($arr2 as $k => $v)
{
$o[$k][] = $v;
}
$result = array_map(function($v){implode(',', array_unique($v));}, $o);
I have two array which i want to merge in a specific way in php.
So i need your help in helping me with it as i tried and failed.
So say i have two arrays:
$array1= array(
"foo" => 3,
"bar" => 2,
"random1" => 4,
);
$array2= array(
"random2" => 3,
"random3" => 4,
"foo" => 6,
);
Now when during merging i would like the common key's values to be added.
So like foo exists in array1 and in array2 so when merging array1 with array 2 i should get "foo" => "9"
I better illustration would be the final array which looks like this:
$array1= array(
"foo" => 9,
"bar" => 2,
"random1" => 4,
"random2" => 3,
"random3" => 4,
);
So again i would like the values of the common keys to be added together and non common keys to be added to array or a new array
I hope i was clear enough
Thanks,
Vidhu
Something like that:
function mergeValues() {
$result = array();
$arraysToMerge = func_get_args();
foreach ($arraysToMerge as $array) {
foreach($array as $key => $value) {
$result[$key] += $value;
}
}
return $result;
}
$res = mergeValues($array1, $array2, $array3); // Can pass any ammount of arrays to a function.
foreach($array1 as $k => $v)
{
If (isset($array2[$k]))
$array1[$k] += $array2[$k];
}
foreach($array2 as $k => $v)
{
If (!isset($array1[$k]))
$array1[$k] = $array2[$k];
}
I built this function in PHP so far called removeAllValuesMatching, but I cannot seem to get it working. I am passing in two parameters $arr and $value. Not sure why this is happening. Any help would be greatly appreciated. This is what I have so far:
<?php
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
function removeAllValuesMatching($arr, $value){
foreach ($arr as $key => $value){
if ($arr[$key] == $value){
unset($arr[$key]);
}
}
return $arr = array_values($arr);
}
print_r(removeAllValuesMatching($arr, "two"));
?>
You're overwriting $value here:
foreach ($arr as $key => $value){
Simply rename it:
foreach ($arr as $key => $val) {
if ($val == $value) {
However, a better way to delete elements from an array is this:
function removeAllValuesMatching(array $arr, $value) {
$keys = array_keys($arr, $value);
foreach ($keys as $key) {
unset($arr[$key]);
}
return $arr;
}
This is my full version, with no variables collision and indenting : that's not an option, you should always indent correctly
<?php
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
function removeAllValuesMatching($arr, $arg){
foreach ($arr as $key => $value){
if ($arr[$key] == $arg){
unset($arr[$key]);
}
}
return $arr = array_values($arr);
}
print_r(removeAllValuesMatching($arr, "two"));
?>
Not a fix for your method, but array_diff will acheive the same result, while also allowing you to remove multiple values.
$arr = [
'a' => "one",
'b' => "two",
'c' => "two",
'd' => "three",
];
$filtered = array_diff($arr, ['one', 'two']);
print_r($filtered); // Array([d] => three)
I have an array that may look like
$arr = array(
array(
'test1' => 'testing1'
),
array(
'test2' => array(
1 =>'testing2
)
);
and I want to turn it into
$newArr = array(
'test1' => 'testing1',
'test2' => array(
1 => 'testing2'
)
);
so i have been trying to shift all array elements up one level.
eidt:
this is my method that combines 2 array together:
public function arrayMerge($arr1, $arr2)
{
foreach($arr2 as $key => $value) {
$condition = (array_key_exists($key, $arr1) && is_array($value));
$arr1[$key] = ($condition ? $this->arrayMerge($arr1[$key], $arr2[$key]) : $value);
}
return $arr1;
}
It's somewhat trivial, many ways are possible.
For example using the array union operator (+)Docs creating the union of all arrays inside the array:
$newArr = array();
foreach ($arr as $subarray)
$newArr += $subarray;
Or by using array_mergeDocs with all subarrays at once via call_user_func_arrayDocs:
$newArray = call_user_func_array('array_merge', $arr);
Try
$arr = array(
array('test1' => 'testing1' ),
array('test2' => array(1 =>'testing2'))
);
$new = array();
foreach($arr as $value) {
$new += $value;
}
var_dump($new);
Output
array
'test1' => string 'testing1' (length=8)
'test2' =>
array
1 => string 'testing2' (length=8)