I have two arrays. One array consists of Id & another array consists of the values & keys. For example. I have a variable called Fruit_id, which consists of:
array(
'fruit_id' => array(
(int) 0 => '3',
(int) 1 => '4'
)
)
and another array called fruits, which consists of:
array(
'values' => array(
(int) 1 => ' Apple',
(int) 2 => 'Banana',
(int) 3 => 'Orange',
(int) 4 => 'Mango'
),
'keys' => array(
(int) 0 => (int) 1,
(int) 1 => (int) 2,
(int) 2 => (int) 3,
(int) 3 => (int) 4
)
)
So, based on fruit_id, I want to have Orange & Mango stored in a variable. How can this be achieved?
as per my understanding you can try below code
$fruits = array();
foreach ($array1['fruit_id'] as $key1 => $value1)
{
foreach ($array2['values'] as $key2 => $value2)
{
if ($value1 == $key2)
{
$fruits[$value1] = $value2;
}
}
}
print_r($fruits);
This will return Array ( [3] => Orange [4] => Mango )
Let me know if this helps you out or any changes needed
You could achieve this easily without even using any loop. Use array_filter() instead.
$array1 = array("fruit_id" => array(3, 4));
$array2 = array(
"values" => array(1 => "Apple",2 => "Banana",3 => "Orange", 4 => "Mango"),
"keys" => array(1,2,3,4)
);
/* Filter elements from $array2['values'] whose keys are present in $array1['fruit_id'] */
$result = array_filter($array2['values'], function($v, $k) use ($array1){
return in_array($k, $array1['fruit_id']);
}, ARRAY_FILTER_USE_BOTH);
echo implode(' & ', $result); // Convert array to string separated by '&'
Related
Is it possible to create a new array from the keys of another like following?
it is a dynamic array chk_values are dynamically changed depends on condition
Array
(
[actBtn] => update
[chkCount] => 5
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
and i want array like this for update database
$chckpoint = Array(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3)
Simply process the original array and only move to the new array where the key starts with chk_
$in = ['actBtn' => 'update',
'chkCount' => 5,
'chk_1' => 2,
'chk_2' => 3,
'chk_3' => 2,
'chk_4' => 3,
'chk_5' => 3
];
foreach($in as $k=>$v){
if ( strpos($k,'chk_') !== false ){ $chckpoint[$k] = $v; }
}
print_r($chckpoint);
RESULT
Array
(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
You can simply take the input array and check for all keys beginning with chk_. If the key matches, take it to the new array.
$chckpoint = [];
foreach($input as $key => $value)
{
if(substr($key, 0, 4) == 'chk_') $chkpoint[$key] = $value;
}
This question already has an answer here:
Convert value from specific multidimensional array key into key in new array with original arrays as value
(1 answer)
Closed 5 months ago.
What's the easiest way to convert
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
to
$b = array(
"a1" => array("id" => 1, "name" => "a1"),
"a2" => array("id" => 2, "name" => "a2")
);
I was expecting PHP have some functional programming facilities to do something like:
$b = map($a, function($item) {
return $item["name"];
});
But I didn't find one.
You can use PHP array_column() function. For your use case, the second argument should be null to return the full array.
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
$b = array_column($a, null, 'name');
and print_r($b) will result in
Array
(
[a1] => Array
(
[id] => 1
[name] => a1
)
[a2] => Array
(
[id] => 2
[name] => a2
)
)
The only solution I see is to loop through the array and create a new array manually.
For example, like this:
$new_array = [];
foreach ($array as $value)
$new_array[$value['name']] = $value;
You can simply do this
$input = [
["id" => 1, "name" => "a1"],
["id" => 2, "name" => "a2"]
];
$result = array_merge(
...array_map(
fn($item) => [$item['name'] => $item],
$input
)
);
Poor me need to implement this in PHP 5.2, and I do not want to use for loop
here's my implementation:
function getField($x) { return $x['name']; }
$ids = array_map('getField', $result);
$result = array_combine($ids, $result);
See if maybe this helps anybody lol
The accepted answer is close, but "close" only counts with hand grenades.
($unique is an indexed array)
$sub_key = 'country';
$new_array = [];
foreach ($unique as $value) {
$new_array[] = [$sub_key => $value];
}
How about:
$a = array(
array('a' => 'a0', 'b' => 'b0', 'c' => 'c0'),
array('a' => 'a1', 'b' => 'b1', 'c' => 'c1'),
array('a' => 'a2', 'b' => 'b2', 'c' => 'c2'),
);
print_r($a);
print_r(array_combine(array_column($a, 'a'), $a));
Where 'a' is the column to use as the associative index.
This leaves the column that becomes the index in the array.
array_column (PHP 5 >= 5.5.0, PHP 7)
array_combine (PHP 5, PHP 7)
I've tried searching for this as I don't think it's that unique that no one has tried to do it. I just can't figure out the right keywords to search for to find my answer!
I have this array
array(
0 => array(
'oranges'=> 4.00,
'apples' => 2.00,
),
1 => array(
'oranges' => 2.00,
'apples' => 1.82,
'peaches' => 1.2,
),
2 => array(
'oranges' => 2.20,
),
);
What I want to do is find the value of all the oranges values multiplied together so (4 * 2 * 2.20) and all the values of apples multiplied together so (2 * 1.82).
The amount of arrays of values is variable and the amount of values inside the arrays is variable.
This uses a combination of foreach, isset, and your run-of-the-mill if/else statements.
$products = array();
foreach ($array as $a) {
foreach ($a as $key => $value) {
if (!isset($products[$key])) $products[$key] = $value;
else $products[$key] = $products[$key] * $value;
}
}
var_dump($products);
Should be self-explanatory since all you're doing is taking the product of all of the lowest level elements with the same keys.
Though sjagr’s answer is the best solution possible, I have an alternative approach with array_column (PHP 5 >= 5.5.0) which requires only one foreach loop:
<?php
$arr = array(
array(
"oranges" => 4.00,
"apples" => 2.00
),
array(
"oranges" => 2.00,
"apples" => 1.82,
"peaches" => 1.2
),
array(
"oranges" => 2.20
)
);
$_arr = array();
foreach(array("oranges", "apples", "peaches") as $val){
$_arr[$val] = array_product(array_column($arr, $val));
}
print_r($_arr);
?>
The result will be:
Array
(
[oranges] => 17.6
[apples] => 3.64
[peaches] => 1.2
)
Demo: https://eval.in/82322
I have two arrays that I want to merge recursively, so adding arrays is not an option. This is simple example without multilevels to demonstrate the problem:
$a1 = Array(
5 => 'pronoun'
)
$a2 = Array(
2 => 'verb',
3 => 'noun'
)
$r = array_merge_recursive($a1, $a2)
And I want to get that resulting array:
Array(
5 => 'pronoun'
2 => 'verb',
3 => 'noun'
)
My problem is that array_merge_recursive function reindixes keys, and I get the following:
Array(
0 => 'pronoun'
1 => 'verb',
2 => 'noun'
)
I understand that's happening because all my keys are numeric. So I tried to make them string when adding but it doesn't seem to be working properly:
$a1[(string)7] = 'some value';
The key - 7 - is still number, or at least that's how it is displayed in debugger - $a1[7] and not $a1['7']. Any advice?
EDIT:
Addition of arrays is not an option. Please see why. I have two multilevel arrays:
$a1 = array (
1 => array (
1 => "man1",
2 => "man"
),
2 => array (
1 => "run",
2 => "nice"
)
);
$a2 = array(
2 => array (
1 => "to observe",
2 => "to examine visually"),
3 => array(
1 => "look nice",
2 => "appear, seem to be"));
$r = $a1 + $a2;
What I expect is the following:
$r = Array(
...
2 => array(
1 => array("run", "to observe")
2 => array("nice", "to examine visually")
));
But instead the options for the key 2 from the second array is not added:
$r = Array(
...
2 => array(
1 => "run",
2 => "nice"
));
you can just use $a1+$a2 to get your result
$a1 = array(
5 => 'pronoun'
);
$a2 = array(
2 => 'verb',
3 => 'noun'
);
print_r($a1+$a2);
For recursive array
$a1 = array(
5 => 'pronoun'
);
$a2 = array(array('a', 'z'), array(2 => 'p', 'q'));
print_r($a1+$a2);
Result is
Array
(
[5] => pronoun
[0] => Array
(
[0] => a
[1] => z
)
[1] => Array
(
[2] => p
[3] => q
)
)
is this what you want to achieve?
This should apply to your particular problem:
function assoc_merge(array $a, array $b)
{
$r = array();
foreach ($a as $key => $val) {
if (array_key_exists($key, $b) && is_array($val) == is_array($b[$key])) {
if (is_array($val)) {
$r[$key] = assoc_merge($a[$key], $b[$key]); // merge array
} else {
$r[$key] = array($val, $b[$key]); // merge entry
}
} else {
$r[$key] = $val; // just copy
}
}
return $r + $b; // add whatever we missed
}
print_r(assoc_merge($a1, $a2));
You can always try the manual case.
function merge () { // takes any number of arguments
$arrays = func_get_args();
$result = array();
foreach ($arrays as $array)
foreach ($array as $key => $item)
if (is_array($item))
$result = merge($result, $item);
else
$result[$key] = $item;
return $result;
Sure, it's slow, but it will work.
$a1 = array(
5 => 'pronoun'
);
$a2 = array(
2 => 'verb',
3 => 'noun'
);
foreach($a2 as $key=>$value) {
$a1[$key] = $value;
}
print_r($a1);
<?php
$a = [ 5 => 'pronoun'];
$b = [ 2 => 'verb', 3 => 'noun'];
$m = array_merge(array_keys($a), array_keys($b));
$final = array_combine($m, array_merge_recursive($a, $b));
print_r($final);
I have two arrays of animals (for example).
$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
How can I merge the two arrays into one by the ID?
#Andy
http://se.php.net/array_merge
That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now.
This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results.
$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?
$array = array(
1 => array(
'name' => 'Cat',
),
2 => array(
'name' => 'Mouse',
)
);
after that you'll have to foreach through one array, performing array_merge on the items of the other:
foreach($array2 as $key=>$value) {
if(!is_array($array[$key])) $array[$key] = $value;
else $array[$key] = array_merge($array[key], $value);
}
Something like that at least. Perhaps there's a better solution?
<?php
$a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));
$b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));
$c = array_merge_recursive($a, $b);
print_r($c);
?>
array_merge_recursive — Merge two or more arrays recursively
outputs:
Array
(
[a] => 1
[b] => Array
(
[t] => 4
[g] => Array
(
[e] => 8
[h] => 5
[v] => 9
)
[0] => 4
)
[c] => 3
)
#Andy
I've already looked at that and didn't see how it can help merge multidimensional arrays. Maybe you could give an example.
#kevin
That is probably what I will need to do as I think the code below will be very slow.
The actual code is a bit different because I'm using ADOdb (and ODBC for the other query) but I'll make it work and post my own answer.
This works, however I think it will be very slow as it goes through the second loop every time:
foreach($array as &$animal)
{
foreach($array2 as $animal2)
{
if($animal['id'] === $animal2['id'])
{
$animal = array_merge($animal, $animal2);
break;
}
}
}
foreach ($array as $a)
$new_array[$a['id']]['name'] = $a['name'];
foreach ($array2 as $a)
$new_array[$a['id']]['age'] = $a['age'];
and this is result:
[1] => Array
(
[name] => Cat
[age] => 123
)
[2] => Array
(
[name] => Mouse
[age] => 321
)
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
With PHP 5.3 you can do this sort of merge with array_replace_recursive()
http://www.php.net/manual/en/function.array-replace-recursive.php
You're resultant array should look like:
Array (
[0] => Array
(
[id] => 2
[name] => Cat
[age] => 321
)
[1] => Array
(
[id] => 1
[name] => Mouse
[age] => 123
)
)
Which is what I think you wanted as a result.
I would rather prefer array_splice over array_merge because of its performance issues, my solution would be:
<?php
array_splice($array1,count($array1),0,$array2);
?>
$new = array();
foreach ($array as $arr) {
$match = false;
foreach ($array2 as $arr2) {
if ($arr['id'] == $arr2['id']) {
$match = true;
$new[] = array_merge($arr, $arr2);
break;
}
}
if ( !$match ) $new[] = $arr;
}