I have Multidimensional array with key value pair so I want to flip i.e key gets to value place and values get to key place but I am getting error
My Php code is:
echo '<pre>',print_r($res),'</pre>';
output when print_r($res):
Array
(
[0] => Array
(
[userid] => 1
)
[1] => Array
(
[userid] => 2
)
[2] => Array
(
[userid] => 3
)
)
getting error in output when want to flip this array:
array_flip(): Can only flip STRING and INTEGER values!
How to solve this?
You are trying to flip a multidimensional array where each value is an array, but according to the docs of array_flip:
Note that the values of array need to be valid keys, i.e. they need to
be either integer or string. A warning will be emitted if a value has
the wrong type, and the key/value pair in question will not be
included in the result.
You could use array_map to use array_flip on each entry:
$a = [
["userid" => 1],
["userid" => 2],
["userid" => 3],
];
$a = array_map("array_flip", $a);
print_r($a);
Result
Array
(
[0] => Array
(
[1] => userid
)
[1] => Array
(
[2] => userid
)
[2] => Array
(
[3] => userid
)
)
See a php demo
array_flip() does not flip array as values. array_flip() can only flip string and integer values.
You can try this:
$arr = [
[ 'userid' => 1 ],
[ 'userid' => 2 ],
[ 'userid' => 3 ]
];
foreach($arr as $a){
$flipped[] = array_flip($a);
}
print_r($flipped);
You can try the following way
$arr = [
[ 'userid' => 1, ],
[ 'userid' => 2, ],
[ 'userid' => 3, ]
];
array_walk($arr, function(&$val) { $val = array_flip($val); });
Related
I have two arrays:
$arr1 = [
[
'id' => 1,
'name' => 'John',
'email' => 'j#mail.com'
],
[
'id' => 2,
'name' => 'Jane',
'email' => 'jane#mail.com'
]
];
And the second array:
$arr2 = [
[
'id' => 1,
'email' => 'john#yahoo.com'
],
[
'id' => 2,
'email' => 'jane#yahoo.com'
],
[
'id' => 2,
'email' => 'jane.doe#hotmail.com'
],
];
I would like to add all values with the same 'id' from the second array to the first array. The result I expect would be:
$arr3 = [
[
'id' => 1,
'name' => 'John',
'email' => ['j#mail.com', 'john#yahoo.com']
],
[
'id' => 2,
'name' => 'Jane',
'email' => ['jane#mail.com', 'jane#yahoo.com', 'jane.doe#hotmail.com']
]
];
This code will do what you want. It goes through all the entries of $arr2, looking for matching id values in $arr1 and, where it finds them, adding the email address from $arr2 to the list of emails in $arr1 for that id value:
foreach ($arr2 as $arr) {
if (($k = array_search($arr['id'], array_column($arr1, 'id'))) !== false) {
if (is_array($arr1[$k]['email'])) {
$arr1[$k]['email'][] = $arr['email'];
}
else {
$arr1[$k]['email'] = array($arr1[$k]['email'], $arr['email']);
}
}
}
Output:
Array (
[0] => Array (
[id] => 1
[name] => John
[email] => Array (
[0] => j#mail.com
[1] => john#yahoo.com
)
)
[1] => Array (
[id] => 2
[name] => Jane
[email] => Array (
[0] => jane#mail.com
[1] => jane#yahoo.com
[2] => jane.doe#hotmail.com
)
)
)
I agree with #Barmar's comment under the question; it will be more direct/efficient and boast a superior computational time complexity to iterate the second array to populate a lookup array and reference it while iterating the first array versus doing full scans and searches of the first array for every row of the second array.
This implementation forms the lookup array using array destructuring syntax in a body-less foreach() loop. Then another foreach() loop iterates the first array using array destructuring syntax, modifying the rows' email element, and checking if there are any emails to add to the first array's email.
Even if no corresponding row exists in the second array, the first array's email string will be cast as a single-element array for consistency.
Code: (Demo)
foreach ($arr2 as ['id' => $id, 'email' => $lookup[$id][]]);
foreach ($arr1 as ['id' => $id, 'email' => &$email]) {
$email = array_merge((array) $email, $lookup[$id] ?? []);
}
var_export($arr1);
The name element does not need to be mentioned during array destructuring because there are no subsequent processes applied to it in the loops.
I have two multidimensional arrays what I want to merge but, I want to skip the same values during merging. I tried several different ways what I find on the web, but nothing help me in my case.
My initial array is much bigger than this one, but here I just put an example:
$array1 = [
"aaa" => [
"aa1"=> [
"key1"=> "value1",
"key2"=> "value2",
],
"bbb"=> [
"bb1",
"bb2",
],
"ccc"=> [
"cc1",
],
],
"ooo" => [
"oo1"
]
];
And another one, which I want to merge in the first one:
$array2 = [
"aaa" => [
"bbb"=> [
"bb2",
],
"ccc"=> [
"cc2",
],
],
];
print_r of the array_merge_recurisive, using the method like:
print_r(array_merge_recursive($array1, $array2));
Array
(
[aaa] => Array
(
[aa1] => Array
(
[key1] => value1
[key2] => value2
)
[bbb] => Array
(
[0] => bb1
[1] => bb2
[2] => bb2
)
[ccc] => Array
(
[0] => cc1
[1] => cc2
)
)
[ooo] => Array
(
[0] => oo1
)
)
So, in the result as you can see array bbb have two bb2 values, but I need just one
The following function will remove duplicate values for an array recursively (edit: only for non-associative keys):
function array_unique_recursive(array $arr) {
if (array_keys($arr) === range(0, count($arr) - 1)) {
$arr = array_unique($arr, SORT_REGULAR);
}
foreach ($arr as $key => $item) {
if (is_array($item)) {
$arr[$key] = array_unique_recursive($item);
}
}
return $arr;
}
You can call it after array_merge_recursive.
Use array_replace_recursive instead of array_merge_recursive.
You can try this
array_unique(array_merge_recursive($array1,$array2), SORT_REGULAR);
hey i have array with returned keys
$temp = $sth->fetchAll(PDO::FETCH_ASSOC);
my result looks like this:
[0] => [
'id' = 11,
'title' => 't1'
]
[1] => [
'id' = 12,
'title' => 't2'
]
if i want to return ids as key i call something like this:
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
and my resoult looks like this:
[11] => [
'title' => 't1'
]
[12] => [
'title' => 't2'
]
how to return array of objects by ID? when i do this i dont have methods in object...
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_CLASS));
I will do a bit easier code like below:-
$fianl_array = array_combine(array_column($temp,'id'),$temp);
Output:- https://eval.in/993728
Reference:-
array_column()
array_combine()
Using foreach:
foreach($input as $k=>$v){
$output[$v['id']] = array('title'=>$v['title']);
}
print_r($output);
Just had to add this as an answer as I believe it's the shortest way of doing this, using array_column() with a third parameter which is the key you want the data indexed by. If you use null as the second parameter, it will index all the data by 'id', you could instead use 'title' and this will only index the title columns by ID...
$output = array_column($temp,null,'id');
Which gives...
Array
(
[11] => Array
(
[id] => 11
[title] => t1
)
[12] => Array
(
[id] => 12
[title] => t2
)
)
This is Actually the original Array
[radios1] => Array
(
[0] => on
)
[from] => Array
(
[0] =>
[1] => Bangalore
[2] =>
[3] =>
)
And i want to remove the empty keys of this array so i used this code to do so
`$array = array_map('array_filter', $_POST);
$array = array_filter($array);`
And the output of this is as follows
[radios1] => Array
(
[0] => on
)
[from] => Array
(
[1] => Bangalore
)
Here i have been able to remove the keys with empty values but the filtered keys should be reindexed. i have used both
array_merge
array_values
`
but there is no use iam getting the same output i want the output has
[radios1] => Array
(
[0] => on
)
[from] => Array
(
[0] => Bangalore
)
please help me with this how i can achieve it
I would use array_walk and then array_filter then array_values to reset the index.
For example:
<?php
$array = [
'radios1' => [
'on'
],
'from' => [
'',
'Bangalore',
'',
'',
]
];
array_walk($array, function (&$value, $key) {
$value = array_values(array_filter($value));
});
print_r($array);
https://3v4l.org/Km1i8
Result:
Array
(
[radios1] => Array
(
[0] => on
)
[from] => Array
(
[0] => Bangalore
)
)
Your coding attempt indicates that you wish to remove all emptyish, falsey, zero-like values using array_filter()'s default behavior on each subarray, then reindex the subarrays, then remove any first level arrays with no children by calling array_filter() again.
When functional programming offers a concise approach, it employs iterated function calls inside of the closure, and will therefore be more expensive than using language constructs to iterate.
The following provides the same functionality without any function calls and never needs to re-index the subarrays because the retained values are indexed as they as pushed into the result array.
Code: (Demo)
$array = [
'radios1' => [
'on',
],
'empty' => [
'',
false,
],
'from' => [
'',
'Bangalore',
null,
0,
]
];
$result = [];
foreach ($array as $key => $items) {
foreach ($items as $item) {
if ($item) {
$result[$key][] = $item;
}
}
}
var_export($result);
Output:
array (
'radios1' =>
array (
0 => 'on',
),
'from' =>
array (
0 => 'Bangalore',
),
)
For anyone who wants to remove empty spaces and nulls, but retains zeros (integer or string typed), then use strlen($item) in the condition.
I have two multidimensional arrays in php and want to merge them.
First one :
array1 = (
0 => array (
0 => array(
id => 1,
name => "test"
)
)
1 => array(...)
)
Second one :
array2 = (
0 => array (
0 => array(
id => 200,
name => "test"
),
1 => array(
id => 201,
name => "test"
)
)
1 => array(...)
)
And the merged array must be like this :
lastArray = (
0 => array (
0 => array(
id =>1,
name => "test"
),
1 => array(
id => 200,
name => "test"
),
2 => array (
id => 201,
name => "test"
)
)
1 => array(...)
)
How should I do this with a proper foreach loop?
According to the lastArray that you've presented - you need to merge the inner arrays only at 0 position/index(and you didn't show how should look a merge result at 1 index).Use the following approach:
$array1[0] = array_merge($array1[0], $array2[0]);
// now, $array1 is your $lastArray
Method 1:
Why not use array_merge or array-merge-recursive for this? This will merge the both (or more) arrays.
$array = array_merge($array1, $array2);
$array = array_merge-recursive($array1, $array2);
Method 2:
Loop through one array.
(You may check if the key is equal to the others array key).
Maybe something like this:
foreach($array_1 as $key=>$value) $array_2[$key] = $value;
Reminder from splash58: Don't forget to use usort in both methods to sort the array by values after sort by id