How to join two arrays in php - php

I have two arrays called $array1 and $array2
and var_dump gives
array (size=1)
0 =>
array (size=5)
'userid' => string '8' (length=1)
'useremail' => string 'venkat#gmail' (length=12)
'username' => string 'venkatesh' (length=9)
'password' => string '1111' (length=4)
'Name' => string 'venkatesh' (length=9)
array (size=1)
'modenames' =>
array (size=3)
0 => string 'group 4' (length=7)
1 => string 'group 4' (length=7)
2 => string 'group 4' (length=7)
now i need to make a json something like this
{
"userid":"8",
"useremail":"venkat#gmail",
"username":"venkatesh",
"password":"1111",
"Name":"venkatesh",
"modenames":{"group 4","group 4","group 4"}
}
i have used array_merge() and $array1+$array2 both gives a json not in above format.. help me out.

In this case you need to,
$t = [
0 => [
'userid' => '8',
'useremail' => 'venkat#gmail',
'username' => 'venkatesh',
'password' => '1111',
'Name' => 'venkatesh'
]
];
$s = [
'modenames' => [
0 => 'group 4',
1 => 'group 4',
2 => 'group 4',
]
];
$t = $t[0] + $s;
// or
array_merge($t[0], $s);

Sum them like this and encode with JSON_FORCE_OBJECT flag:
$j = json_encode($array1[0]+$array2,JSON_FORCE_OBJECT);
Result:
{"userid":8,"useremail":"venkat#gmail","username":"venkatesh","password":"1111","Name":"venkatesh","modenames":{"0":"group4","1":"group4","2":"group4"}}

Try this
$array3 = $array1[0];
$array3['modenames'] = $array2['modenames'];
json_encode($array3);
JSON String =
{"userid":8,
"useremail":"venkat#gmail",
"username":"venkatesh",
"password":"1111",
"Name":"venkatesh",
"modenames":["group 4","group 4","group 4"]
}
As an print_r()
stdClass Object
(
[userid] => 8
[useremail] => venkat#gmail
[username] => venkatesh
[password] => 1111
[Name] => venkatesh
[modenames] => Array
(
[0] => group 4
[1] => group 4
[2] => group 4
)
)
Of course your requirement for
"modenames":{"group 4","group 4","group 4"}
cannot work as you will either need an array occurance as per my example or if you made it an object there would have to be a unique property name one for each of the 3 data items as well as the data.

try with the merge function php. if that is good for you
$array3= array_merge($array1, $array2);

Related

Re-grouping array into multidimensional using several values

What I have:
array(
[
'id' => 12, 'group' => 'abc', 'name' => 'Lorem',
],
[
'id' => 12, 'group' => 'def', 'name' => 'Ipsum',
],
[
'id' => 34, 'group' => 'ghi', 'name' => 'Dolor',
],
[
'id' => 34, 'group' => 'jkl', 'name' => 'Sit',
],
[
'id' => 34, 'group' => 'mno', 'name' => 'Amet',
],
);
What I want:
array (size=2)
12 =>
array (size=2)
'abc' =>
array (size=3)
'id' => int 12
'group' => string 'abc' (length=3)
'name' => string 'Lorem' (length=5)
'def' =>
array (size=3)
'id' => int 12
'group' => string 'def' (length=3)
'name' => string 'Ipsum' (length=5)
34 =>
array (size=3)
'ghi' =>
array (size=3)
'id' => int 34
'group' => string 'ghi' (length=3)
'name' => string 'Dolor' (length=5)
'jkl' =>
array (size=3)
'id' => int 34
'group' => string 'jkl' (length=3)
'name' => string 'Sit' (length=3)
'mno' =>
array (size=3)
'id' => int 34
'group' => string 'mno' (length=3)
'name' => string 'Amet' (length=4)
What I tried:
The obvious:
$sorted = array();
foreach ($products as $product) {
$sorted[$product['id']][$product['group']] = $product;
}
$products = $sorted;
unset($sorted);
But then, in an effort to avoid foreach() loops, and with help of #atomrc's answer to How to group subarrays by a column value?, I came up with this:
$sorted = array_reduce($products, function ($accumulator, $element) {
$accumulator[$element['id']][] = $element;
return $accumulator;
}, []);
array_walk($sorted, function(&$item) {
$item = array_reduce($item, function ($accumulator, $element) {
$accumulator[$element['group']] = $element;
return $accumulator;
}, []);
});
So while the above looks cool and all, it's also much bigger and seemingly more complex than that foreach. This is probably because my experience with array_reduce() is limited. Is there a way to have the array grouped in one go? For example, in the first array_reduce() call.
Personally I don't see an issue with the foreach solution, but if you want to use array_reduce you can simply use the inner code from the foreach loop:
$grouped = array_reduce($products, function ($c, $v) {
$c[$v['id']][$v['group']] = $v;
return $c;
}, []);
print_r($grouped);
The output of this code is the same as your foreach loop.
Note that this (and your foreach loop) won't deal correctly with the situation where there is more than one array with the same id and group values. For example, if we extend $products:
$products[] = [
'id' => 34, 'group' => 'jkl', 'name' => 'Consectetur',
];
Then the first jkl group value gets overwritten by the second. To deal with this you need to make each group an array e.g.
$grouped = array_reduce($products, function ($c, $v) {
$c[$v['id']][$v['group']][] = $v;
return $c;
}, []);
print_r($grouped);
In this case the jkl group then looks like:
[jkl] => Array
(
[0] => Array
(
[id] => 34
[group] => jkl
[name] => Sit
)
[1] => Array
(
[id] => 34
[group] => jkl
[name] => Consectetur
)
)
Demo on 3v4l.org

Search through an array with two values

Good day,
I'm trying to search through an array.
I have two IDs (productId, secondaryProductId) in an array ($package) with some other data:
array (size=7)
'title' => string 'Compleet' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '58.75' (length=5)
I have an array with arrays ($availableProducts):
array (size=2)
0 =>
array (size=3)
'product_id' => int 102
'description' => string 'some description for 102'
'order_link' => string 'some/link/102'
1 =>
array (size=3)
'product_id' => int 150
'description' => string 'some description for 150'
'order_link' => string 'some/link/150'
2 =>
array (size=3)
'product_id' => int 160
'description' => string 'some description for 160'
'order_link' => string 'some/link/160'
3 =>
array (size=3)
'product_id' => int 140
'description' => string 'some description for 140'
'order_link' => string 'some/link/140'
What I want to achieve is to search both product IDs in the $availableProducts array.
If they exists (like 102 and 150 with there description and link exist) I want the description and link to be set in the first array where both the product IDs are.
Like this:
array (size=7)
'title' => string 'Complete' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string '150'
'secondaryPrice' => string '58.75'
'description' => string 'some description for 102'
'order_link' => string 'link/for/102'
'secondaryDescription' => string 'some description for 150'
'secondaryOrder_link' => string 'some/link/150'
If one of them doesn't exist I want it's ID and price to either be removed or set as an empty string (doesn't matter).
Like this:
array (size=7)
'title' => string 'Complete' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string ''
'secondaryPrice' => string ''
'description' => string 'some description for 102'
'order_link' => string 'link/for/102'
What I have tried so far with a foreach loop:
$finalArray = array();
foreach ($availableProducts as $product) {
if ($package['productId'] == $product->product_id) {
$package['orderLink'] = $product->order_link;
$finalArray[] = $package;
}
if ($package['secondaryProductId'] == $product->product_id) {
$package['secondaryOrderLink'] = $product->order_link;
$finalArray[] = $package;
}
}
But it doesn't work. At first it looks fine to set the orderLink, but then it kind of runs double:
array (size=2)
0 =>
array (size=5)
'productId' => string '102' (length=5)
'price' => string '35.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '48.75' (length=5)
'orderLink' => string 'link/for/102'
1 =>
array (size=6)
'productId' => string '102' (length=5)
'price' => string '35.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '48.75' (length=5)
'orderLink' => string 'link/for/102'
'secondaryOrderLink' => string 'link/for/150'
I've tried playing around a bit, also tried in_array. But I clearly do something wrong. Any help will be highly appreciated.
Here you go (truncated version)
$availableProducts = [
0 => [
'product_id' => 102,
'description' => 'some description for 102',
'order_link' => 'some/link/102',
], 1 => [
'product_id' => 150,
'description' => 'some description for 150',
'order_link' => 'some/link/150'
], 2 => [
'product_id' => 160,
'description' => 'some description for 160',
'order_link' => 'some/link/160'
]
];
$array1 = [
'title' => 'Compleet',
'productId' => '102',
'price' => '45.75',
'secondaryProductId' => '150',
'secondaryPrice' => '58.75',
];
print_r(
array_intersect_key(
array_column($availableProducts, null, 'product_id'),
array_flip([$array1['productId'], $array1['secondaryProductId']])
)
);
Output
Array
(
[102] => Array
(
[product_id] => 102
[description] => some description for 102
[order_link] => some/link/102
)
[150] => Array
(
[product_id] => 150
[description] => some description for 150
[order_link] => some/link/150
)
)
Sandbox
note - this only works if product_id is unique in $availableProducts
Basically array_column($availableProducts, null, 'product_id') will restructure your array using product_id as the key (no duplicate ids), then you can get the intersection between this and an array with the 2 id's you need to find. I filped it because I am to lazy to make them as keys, which they need to be for array_intersect_key (obviously) to work.
array_column - is extremely powerful for array to array comparison. There are several neat tricks you can do with it...
The above shows you how to filter out only the 2 you want, But if you just want to update the original array ($array1 in this example) is a simple matter of doing this:
$res = array_column($availableProducts, null, 'product_id');
$array1['productId'] = $res[$array1['productId']]['description'];
$array1['secondaryProductId'] = $res[$array1['secondaryProductId']]['description'];
Output
Array
(
[title] => Compleet
[productId] => some description for 102
[price] => 45.75
[secondaryProductId] => some description for 150
[secondaryPrice] => 58.75
)
Sandbox
See with the product ID's as the keys (see output from example one) we can just use the value to get that segment of the multi-dimensional array by it's product_id - directly.
Obviously it's pretty easy to do this too now
$res = array_column($availableProducts, null, 'product_id');
$array1['productId'] =['description' => $res[$array1['productId']]['description'], 'order_link' => $res[$array1['productId']]['order_link']];
$array1['secondaryProductId'] =['description' => $res[$array1['secondaryProductId']]['description'], 'order_link' => $res[$array1['secondaryProductId']]['order_link']];
Output:
Array
(
[title] => Compleet
[productId] => Array
(
[description] => some description for 102
[order_link] => some/link/102
)
[price] => 45.75
[secondaryProductId] => Array
(
[description] => some description for 150
[order_link] => some/link/150
)
[secondaryPrice] => 58.75
)
I'm not sure what you want as the end result, but maybe this will help you.
Enjoy

Remove array entry with one or more duplicate values in multidimensional array

How can I remove an array entry with one or more duplicate values in multidimensional array? For example if I have:
array (size=4)
0 =>
array (size=3)
'food' => string 'bread' (length=5)
'color' => string 'white' (length=5)
'language' => string 'php' (length=3)
1 =>
array (size=3)
'food' => string 'rice' (length=4)
'color' => string 'purple' (length=6)
'language' => string 'c#' (length=2)
2 =>
array (size=3)
'food' => string 'pasta' (length=5)
'color' => string 'red' (length=3)
'language' => string 'php' (length=3)
3 =>
array (size=3)
'food' => string 'steak' (length=5)
'color' => string 'yellow' (length=6)
'language' => string 'ruby' (length=4)
Since there is a php entry in array[2], I want to delete the entire record so that I can have
array (size=4)
0 =>
array (size=3)
'food' => string 'bread' (length=5)
'color' => string 'white' (length=5)
'language' => string 'php' (length=3)
1 =>
array (size=3)
'food' => string 'rice' (length=4)
'color' => string 'purple' (length=6)
'language' => string 'c#' (length=2)
2 =>
array (size=3)
'food' => string 'steak' (length=5)
'color' => string 'yellow' (length=6)
'language' => string 'ruby' (length=4)
I have tried this code:
array_map("unserialize", array_unique(array_map("serialize", $array)));
and it doesn't work. What am I doing wrong?
Since your objects are all different (for instance, they all have different colors), array_unique will not reduce the number of elements.
Instead, key your array elements by their language property: that will eliminate duplicate php entries, and then convert that associated array back to an indexed one:
foreach($array as $row) {
$result[$row['language']] = $row;
}
$result = array_values($result);
The solution using array_intersect and array_merge functions (will cover duplicates for all keys):
$arr = [
['food' => 'bread', 'color' => 'white', 'language' => 'php'],
['food' => 'rice', 'color' => 'purple', 'language' => 'c#'],
['food' => 'pasta', 'color' => 'red', 'language' => 'php'],
['food' => 'steak', 'color' => 'yellow', 'language' => 'ruby']
];
$values = []; // auxiliary array
foreach ($arr as $k => $a) {
if (array_intersect($values, $a)){
unset($arr[$k]); // removing the whole `entry` if it contains duplicates in any key
} else {
$values = array_merge($values, array_values($a));
}
}
print_r($arr);
The output:
Array
(
[0] => Array
(
[food] => bread
[color] => white
[language] => php
)
[1] => Array
(
[food] => rice
[color] => purple
[language] => c#
)
[3] => Array
(
[food] => steak
[color] => yellow
[language] => ruby
)
)

Append an array to an existing array by index value?

I have an array like this:
Array (
[0] => 10060127
[1] => 10065127
[2] => 10070127
[3] => 10075127
)
I want to add an associative array based on the value in the array. e.g. find 10070127 and an an associative array to it containing various other info. Something like:
[1] => 10065127 => Time : 10:00
Date : 16/12/2014
Count : 1
How can I recognise the correct position and push these items to this array?
You can try this:
$dataArray = array(
0 => 10060127,
1 => 10065127,
2 => 10070127,
3 => 10075127
);
$toAdd = array(
1 => array(
10065127 => array("Time" => '10:00',
"Date" => '16/12/2014',
"Count" => '1'
)
),
2 => array(
10070127 => array("Time" => '17:25',
"Date" => '11/12/2014',
"Count" => '95'
)
)
);
foreach ($toAdd as $subArray) {
$toSearch = key($subArray);
$pos = array_search($toSearch, $dataArray);
if ($pos !== false) {
unset($dataArray[$pos]);
$dataArray[$toSearch] = $subArray[$toSearch];
}
}
var_dump ($dataArray);
Output will be:
array
0 => int 10060127
3 => int 10075127
10065127 =>
array
'Time' => string '10:00' (length=5)
'Date' => string '16/12/2014' (length=10)
'Count' => string '1' (length=1)
10070127 =>
array
'Time' => string '17:25' (length=5)
'Date' => string '11/12/2014' (length=10)
'Count' => string '95' (length=2)
Something like:
$id = '10070127';
$array[array_search($id, $array)] = array($id=>array(
'time'=>'10:00',
'Date'=>'16/12/2014',
'Count'=>1));

Sort php different format multidimensional array on key

I have an array like this
Array
(
[name] => Array
(
[0] => img/test240.jpg
[1] => img/cs1.jpg
[2] => img/cs2.jpg
[3] => img/cs3.jpg
)
[link] => Array
(
[0] => http://google.com
[1] => http://google.com
[2] => http://facebook.com
[3] => http://orkut.com
)
[order] => Array
(
[0] => 4
[1] => 1
[2] => 2
[3] => 3
)
)
I need to sort it by order WHICH IS KEY in Multidimensional array. Here is output.
Array
(
[name] => Array
(
[1] => img/cs1.jpg
[2] => img/cs2.jpg
[3] => img/cs3.jpg
[0] => img/test240.jpg
)
[link] => Array
(
[1] => http://google.com
[2] => http://facebook.com
[3] => http://orkut.com
[0] => http://google.com
)
[order] => Array
(
[1] => 1
[2] => 2
[3] => 3
[0] => 4
)
)
In this you can see when order is sorted name and link is also sorted according to the order. How can i do this with php.
You have to use array_map() in conjunction with sort().
If you want to preserve actual element order you have to use asort() instead sort().
Try this code:
$arr = array(
'name' => array(
0 => 'img/test240.jpg',
1 => 'img/cs1.jpg',
2 => 'img/cs2.jpg',
3 => 'img/cs3.jpg',
),
'link' => array(
0 => 'http://google.com',
1 => 'http://google.com',
2 => 'http://facebook.com',
3 => 'http://orkut.com',
),
'order' => array(
0 => 4,
1 => 1,
2 => 2,
3 => 3,
),
);
function mysort($a) {
asort($a);
return $a;
}
$arr = array_map('mysort', $arr);
print_r($arr);
Demo.
Try this, it uses array_multisort:
$array holds:
array (size=3)
'name' =>
array (size=4)
0 => string 'img/test240.jpg' (length=15)
1 => string 'img/cs1.jpg' (length=11)
2 => string 'img/cs2.jpg' (length=11)
3 => string 'img/cs3.jpg' (length=11)
'link' =>
array (size=4)
0 => string 'http://google.com' (length=17)
1 => string 'http://google.com' (length=17)
2 => string 'http://facebook.com' (length=19)
3 => string 'http://orkut.com' (length=16)
'order' =>
array (size=4)
0 => string '4' (length=1)
1 => string '1' (length=1)
2 => string '2' (length=1)
3 => string '3' (length=1)
Code:
$sort = array();
foreach($array as $k) {
foreach($k as $ind=>$val){
$sort['name'][$ind] = $array['name'][$ind];
$sort['link'][$ind] = $array['link'][$ind];
$sort['order'][$ind] = $array['order'][$ind];
}
}
array_multisort($sort['order'], SORT_ASC, $sort['link'], SORT_ASC, $sort['name'], SORT_ASC);
var_dump($sort);
Output:
array (size=3)
'name' =>
array (size=4)
0 => string 'img/cs1.jpg' (length=11)
1 => string 'img/cs2.jpg' (length=11)
2 => string 'img/cs3.jpg' (length=11)
3 => string 'img/test240.jpg' (length=15)
'link' =>
array (size=4)
0 => string 'http://google.com' (length=17)
1 => string 'http://facebook.com' (length=19)
2 => string 'http://orkut.com' (length=16)
3 => string 'http://google.com' (length=17)
'order' =>
array (size=4)
0 => string '1' (length=1)
1 => string '2' (length=1)
2 => string '3' (length=1)
3 => string '4' (length=1)
$this_arr = array(1,2,3,0);
function my_sort_2($arr, $arrangement)
{
$flag = false;
foreach($arr as $key => $val)
{
if(is_array($arr[$key]))
{
$arr[$key] = my_sort_2($arr[$key],$arrangement);
$flag = true;
}
}
if($flag == false && is_array($arr) && is_assoc($arr) === false)
{
$temp = array();
for($i = 0; $i < count($arrangement); $i++)
{
if(isset($arr[$arrangement[$i]]))
{
$temp[$arrangement[$i]] = $arr[$arrangement[$i]];
unset($arr[$arrangement[$i]]);
}
}
//$arr = array_merge($temp,$arr);
$arr = $temp;
}
return $arr;
}
Include this function below to run my own function. Also credit to #Matt Whittingham where i got this code from
function is_assoc($array)
{
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
Now let's do some sortin'... print_r(my_sort_2($arr,$this_arr)); assuming $arr contains Shan's array.
The output is EXACTLY what you desired.
It'll search for nested array (at least intended) and see if it's in a standard numeric ordered keys (in short, not custom order - yet; and not assoc) then sort it the way you want.
Note: I know my code isn't that probably good, optimized or bug free and that's my second attempt, misunderstanding your requirements first time (see the function name?).
Well after some research i found a simple solution like this
asort($data['order']);
$keys = array_keys($data['order']);
$data['name'] = array_replace(array_flip($keys), $data['name']);
$data['link'] = array_replace(array_flip($keys), $data['link']);
$data['order'] = array_replace(array_flip($keys), $data['order']);
Although i dont want to apply array_replace and array_flip on all the keys but this is done for the time being. I will surely trying to find how i can do it with single instruction.

Categories