Move array with same value inside the same array - php

This is my array.
Array
(
[id] => 1
[color] => "White"
[something] => Array
(
[country] => "France"
[city] => "Paris"
)
)
Array
(
[id] => 2
[color] => "Black"
[something] => Array
(
[country] => "Germany"
[city] => "Berlin"
)
)
Array
(
[id] => 2
[color] => "Red"
[something] => Array
(
[country] => "Russia"
[city] => "Moscow"
)
)
I want to group arrays with same id value. This should be the output:
[0] => Array
(
[0] => Array
(
[id] => 1
[color] => "White"
[something] => Array
(
[country] => "France"
[city] => "Paris"
)
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[color] => "Black"
[something] => Array
(
[country] => "Germany"
[city] => "Berlin"
)
)
[1] => Array
(
[id] => 2
[color] => "Red"
[something] => Array
(
[country] => "Russia"
[city] => "Moscow"
)
)
)
I tried with tens of foreach statements but there's no way for me to get arrays with same id inside the same array. Is it probably related with the fact that it's a multidimensional array? Should I use 2 nested foreach to get the result?

Code:
<?php
$arr = array(
array(
'id' => 1,
'color' => 'white',
'something' => array(
'country' => 'France',
'city' => 'Paris',
),
),
array(
'id' => 2,
'color' => 'Black',
'something' => array(
'country' => 'Germany',
'city' => 'Berlin',
),
),
array(
'id' => 2,
'color' => 'Red',
'something' => array(
'country' => 'Russia',
'city' => 'Moscow',
),
),
);
function groupify($arr) {
$new = array();
foreach ($arr as $item) {
if (!isset($new[$item['id']])) {
$new[$item['id']] = array();
}
$new[$item['id']][] = $item;
}
return $new;
}
print_r(groupify($arr));
Result:
Array
(
[1] => Array
(
[0] => Array
(
[id] => 1
[color] => white
[something] => Array
(
[country] => France
[city] => Paris
)
)
)
[2] => Array
(
[0] => Array
(
[id] => 2
[color] => Black
[something] => Array
(
[country] => Germany
[city] => Berlin
)
)
[1] => Array
(
[id] => 2
[color] => Red
[something] => Array
(
[country] => Russia
[city] => Moscow
)
)
)
)
if you don't want to preserve keys, just call array_values before return.

Use id for key of new array.
$a[$array[id]][] = $array;

If you wanted to use a foreach:
<?php
$return = array();
foreach($array as $key => $innerArray) {
$return[$innerArray['id']][]= $innerArray;
}
Now $return contains them groped by ID, where keys 1 and 2 are your IDs
array(
1 => array(
array(/** **/)
),
2 => array(
array(/** **/),
array(/** **/)
);
);
You can then access your groups like this:
foreach($return as $key => $groupArray) {
// you have the groups here
foreach($groupArray as $id => $singleArray) {
// singleArray contains your id, colour etc
}
}
foreach($return[1] as $groupOne) {
// all arrays with id = 1
}

Related

searching a key value in multidimensional array in php

Am totally confused with the multidimensional arrays in php. I have a very big array in which am trying to do some search. That is if the colour is green, check for the age and resultant array should contain 4 highest value of age with colour green and all other subarrays should be unaffected. Please help
Array
(
[0] => Array
(
[name] => arr1
[data] => Array
(
[0] => Array
(
[name] => A
[age] => 5
[color] => green
)
[1] => Array
(
[name] => B
[age] => 4
[color] => green
)
[2] => Array
(
[name] => C
[age] => 10
[color] => Red
)
[3] => Array
(
[name] => F
[age] => 1
[color] => green
)
)
)
[1] => Array
(
[name] => arr2
[data] => Array
(
[0] => Array
(
[name] => cc
[age] => 8
[color] => yellow
)
[1] => Array
(
[name] => Y
[age] => 20
[color] => green
)
[2] => Array
(
[name] => Y
[age] => 9
[color] => green
)
)
)
)
Expected resultant array is
Array
(
[0] => Array
(
[name] => arr1
[data] => Array
(
[0] => Array
(
[name] => A
[age] => 5
[color] => green
)
[1] => Array
(
[name] => B
[age] => 4
[color] => green
)
[2] => Array
(
[name] => C
[age] => 10
[color] => Red
)
)
)
[1] => Array
(
[name] => arr2
[data] => Array
(
[0] => Array
(
[name] => cc
[age] => 8
[color] => yellow
)
[1] => Array
(
[name] => Y
[age] => 20
[color] => green
)
[2] => Array
(
[name] => Y
[age] => 9
[color] => green
)
)
)
)
<?php
// Your code here!
$ar[0] = array('name' => 'arr1',
'data' => array
(
'0' => array
(
'name' => 'A',
'age' => 5,
'color' => 'green'
),
'1' => array
(
'name' => 'B',
'age' => 4,
'color' => 'green'
),
'2' => array
(
'name' => 'C',
'age' => 10,
'color' => 'Red'
),
'3' => array
(
'name' => 'F',
'age' => 1,
'color' => 'green'
)
)
);
$ar[1] = array
(
'name' => 'arr2',
'data' => array
(
'0' => array
(
'name' => 'cc',
'age' => 8,
'color' => 'yellow'
),
'1' => array
(
'name' => 'Y',
'age' => 20,
'color' => 'green'
),
'2' => array
(
'name' => 'Y',
'age' => 9,
'color' => 'green'
)
)
);
$green = array();
foreach($ar as $k1=>$a1){
foreach($a1['data'] as $k2=>$a2){
if($a2['color']=='green') {
array_push($green,$a2['age']);
}
}
}
rsort($green);
$green = array_splice($green,0,4);
foreach($ar as $k1=>$a1){
foreach($a1['data'] as $k2=>$a2){
if($a2['color']=='green') {
if(!in_array($a2['age'], $green)){
unset($ar[$k1]['data'][$k2]);
}
}
}
}
print_r($ar);
?>

Group Array by category

I am facing problem In grouping array with the Key:-
I have an php array Which has following elecment in it.
$array = array(
'0' => array ( 'id' => 'food,Travel', 'names' => 'chimpanzee' ),
'1' => array ( 'id' => 'food', 'name' => 'meeting' ),
'2' => array ( 'id' => 'Z1', 'name' => 'dynasty' ),
'3' => array ( 'id' => 'X', 'name' => 'chocolate' ),
'4' => array ( 'id' => 'Travel', 'name' => 'bananas' ),
'5' => array ( 'id' => 'Travel', 'name' => 'fantasy' ),
'6' => array ( 'id' => 'Travel', 'name' => 'football' )
);
When I try with following code:-
$newarray= array();
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
I am getting below result Array Here food,travel is created another array but I want to please those to respective category "Food goes to food" and travel goes to travel"
(
[food,Travel] => Array
(
[0] => Array
(
[id] => food,Travel
[names] => chimpanzee
)
)
[food] => Array
(
[1] => Array
[id] => food,Travel
[names] => chimpanzee
)
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
But I am want following result:- Food should Go to food category and travels should go to travels category like:-
Array
(
[food] => Array
(
// Food should come at food category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
(
[1] => Array
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
( // Travel should come at travel category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
When id has ,, just explode it, check the demo
$result = [];
foreach($array as $k => $v){
if(strpos($v["id"],",")) {
$ids = explode(",", $v["id"]);
foreach ($ids as $id) {
$result[$id][$k] = $v;
}
}else{
$result[$v["id"]][$k] = $v;
}
}
var_dump($result);
No need to make it complex, like some have suggested, use explode()
https://3v4l.org/jVK6j
$newarray= [];
foreach($array as $key => $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$newarray[$category][$key] = $value;
$newarray[$category][$key]["id"] = $category;
}
} else {
$newarray[$value["id"]][$key] = $value;
}
}
var_dump($newarray);
You could even remove $key since these will be auto incremented.
foreach($array as $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$value["id"] = $category;
$newarray[$category][] = $value;
}
} else {
$newarray[$value["id"]][] = $value;
}
}

PHP array with n level deep

Assuming I have an array and recursively want to do some task. I have spent one day for this unable to solve this. May be my logic is not good.
Any help on how to do such thing in an efficient way would save my days.
I have an array with n level deep, looking like:
Array
(
[0] => Array
(
[name] => user1
[email] => user1#demo.com
[depth] => 1
)
[1] => Array
(
[name] => user2
[email] => user2#demo.com
[depth] => 1
[0] => Array
(
[0] => Array
(
[name] => user2.1
[email] => user2.1#demo.com
[depth] => 2
)
)
)
[2] => Array
(
[name] => user3
[email] => user3#demo.com
[depth] => 1
[0] => Array
(
[0] => Array
(
[name] => user3.1
[email] => user3.1#demo.com
[depth] => 2
[0] => Array
(
[0] => Array
(
[name] => user3.1.1
[email] => user3.1.1#demo.com
[depth] => 3
)
)
)
[1] => Array
(
[name] => user3.2
[email] => user3.2#demo.com
[depth] => 2
)
)
)
)
I want to change above array in exactly this format:
array(
0 => array(
'name' => 'user1',
),
1 => array(
'name' => 'user2',
'children' => array(
0 => array(
'name' => 'user2.1',
) ,
) ,
) ,
2 => array(
'name' => 'user3',
'children' => array(
0 => array(
'name' => 'user3.1',
'children' => array(
0 => array(
'name' => 'user3.1.1',
) ,
) ,
) ,
1 => array(
'name' => '3.2',
)
) ,
) ,
)
Edited:
I am using this code and working fine if i want to show data in tree format but unable to push data into array as i want.
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
displayArrayRecursively($value, $indent . '-->');
} else {
if ($key == 'name')
{
echo "$indent $value <br>";
}
else {
continue;
}
}
}
}
}
displayArrayRecursively($userListArray);
Can anyone suggest me how to do this?
Thank you
This function will do what you want:
function process_nodes($nodes) {
$new = array();
foreach ($nodes as $node) {
$new[] = array('name' => $node['name']);
if (isset($node[0])) {
$new[count($new)-1]['children'] = process_nodes($node[0]);
}
}
return $new;
}
print_r(process_nodes($data));
Output:
Array
(
[0] => Array
(
[name] => user1
)
[1] => Array
(
[name] => user2
[children] => Array
(
[0] => Array
(
[name] => user2.1
)
)
)
[2] => Array
(
[name] => user3
[children] => Array
(
[0] => Array
(
[name] => user3.1
[children] => Array
(
[0] => Array
(
[name] => user3.1.1
)
)
)
[1] => Array
(
[name] => user3.2
)
)
)
)

How to Merge Arrays with WHERE Clause?

How to add 2nd array into 1st array where [ myid ] matches.
1st Array
Array
(
[0] => Array
(
[myid] => 70
[realname] => Kishore
[full_name] => Kishore Chandra
[category] => professional
[firm_name] => Yes
[designation] => Mechanical
[address] => Dwarakanagar 5th lane
[city] => Vishakhapatnam
[email] => yesapps.india#gmail.com
)
[1] => Array
(
[myid] => 75
[realname] => Vinod kumar
[full_name] => Kishore Chandra
[category] => professional
[firm_name] =>
[designation] =>
[address] =>
[city] =>
[email] => vinod.k.alluri#gmail.com
)
)
2nd Array
Need these projects to be added into Array 1
Array
(
[0] => Array
(
[myid] => 70
[projects] => 20
)
[1] => Array
(
[myid] => 75
[projects] => 43
)
)
I have tried to Merge Array's but no use, i am getting 2 more objects in to this array
I hope my requirement is clear and readable, if not please mention in comment so i could explain it more.
The answer can be in codeigniter also i am using Codeigniter framework
assume that you want the result array to be merging the projects to your first array
you want the result set to be like this
Array
(
[0] => Array
(
[myid] => 70
[realname] => Kishore
[full_name] => Kishore Chandra
[category] => professional
[firm_name] => Yes
[designation] => Mechanical
[address] => Dwarakanagar 5th lane
[city] => Vishakhapatnam
[email] => yesapps.india#gmail.com
[projects] => 20
)
[1] => Array
(
[myid] => 75
[realname] => Vinod kumar
[full_name] => Kishore Chandra
[category] => professional
[firm_name] =>
[designation] =>
[address] =>
[city] =>
[email] => vinod.k.alluri#gmail.com
[projects] => 43
)
)
so try this code
foreach($b as $key => $val){
if(isset($a[$key]) && $a[$key]->myid == $val->myid){
$a[$key]->projects = $val->projects;
}
}
if converted the stdArray to Array
json_decode($a,TRUE)
and json_decode($b, TRUE)
$a = Array
(
0 => Array
(
'myid' => 70,
'realname' => 'Kishore',
'full_name' => 'Kishore Chandra',
'category' => 'professional',
'firm_name' => 'Yes',
'designation' => 'Mechanical',
'address' => 'Dwarakanagar 5th lane',
'city' => 'Vishakhapatnam',
'email' => 'yesapps.india#gmail.com',
),
1 => Array
(
'myid' => 75,
'realname' => 'Vinod kumar',
'full_name' => 'Kishore Chandra',
'category' => 'professional',
'firm_name' => '',
'designation' => '',
'address' => '',
'city' => '',
'email' => 'vinod.k.alluri#gmail.com'
)
);
$b = Array ( 0 => Array(
'myid' => 70,
'projects' => 20
),
1 => Array(
'myid' => 75,
'projects' => 43
)
);
foreach($b as $key => $val){
if(isset($a[$key]) && $a[$key]['myid'] == $val['myid']){
$a[$key]['projects'] = $val['projects'];
}
}
print_r($a);
NOTE:
$b is the 2nd array
$a is the 1st array
foreach($array1 as $key => $array){
foreach($array as $key2 => $value){
$results[$key]['myid'] = $value;
}
}
foreach($array2 as $key => $array){
foreach($array as $key3 => $value){
$results[$key3]['projects'] = $value;
}
}
print_r($results);

How can I sort multidimensional array through key

Array
(
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 14
[name] => Volvo
)
[1] => Array
(
[id] => 15
[name] => Mercedes-Benz
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 16
[name] => Naruto
)
[1] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
)
)
[18] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
)
Guys I want to sort the values of this array, i want to sort it by key and the key is 'name'. This should sort the first level and the second level thru key 'name'.
This array i put in print_r() so it looks like this. The array is not fix so i can add in the future.
So after sorting the final value of the array is...
Array
(
[18] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
[12] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 15
[name] => Mercedes-Benz
)
[1] => Array
(
[id] => 14
[name] => Volvo
)
)
)
[13] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
[1] => Array
(
[id] => 16
[name] => Naruto
)
)
)
)
And this is the array in code.
$categories = array(
12 =>
array('id' =>12,
'name' => 'Car',
'children' =>
array(
array('id' => 14,
'name' => 'volvo'
)
),
array(
array('id' => 15,
'name' => 'Mercedez-Benz'
)
)
),
13 =>
array('id' =>13,
'name' => 'Manga',
'children' =>
array(
array('id' => 16,
'name' => 'Naruto'
)
),
array(
array('id' => 17,
'name' => 'Hunter X Hunter'
)
)
),
18=>
array('id' => 18,
'name'=> 'aa',
'children' => array())
);
echo "<pre>";
print_r($categories);
the 'name' is not your real 'Key', just saying, because 'key' in Php normally means the name of your array, like '18' and '12' in your array and so on, like this:
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
in this example, the result will be:
a = orange
b = banana
c = apple
d = lemon
anyway to answer your question on how to sort it on 'name', use 'usort':
function cmp($a, $b) {
return $a['name'] - $b['name'];
}
usort($arr,"cmp");
check out the following link for further information:
How do I sort a PHP array by an element nested inside?
if using php 5.3+ you can use closures in your code and sort like this
usort($categories,function($a,$b){
return $a['name'] - $b['name']
}
So,
I'm going to try and explain it better to you
your array is big, yes, but you want to sort only on the key value '[name]'.
In my test I used the array you provided:
$categories = array(
12 =>
array('id' =>12,
'name' => 'Car',
'children' =>
array(
array('id' => 14,
'name' => 'volvo'
)
),
array(
array('id' => 15,
'name' => 'Mercedez-Benz'
)
)
),
13 =>
array('id' =>13,
'name' => 'Manga',
'children' =>
array(
array('id' => 16,
'name' => 'Naruto'
)
),
array(
array('id' => 17,
'name' => 'Hunter X Hunter'
)
)
),
18=>
array('id' => 18,
'name'=> 'aa',
'children' => array())
);
if the array is declared, you can add the usort like this:
usort($categories,"sortByName");
the first element in the above ($categories), is your array, the second element will provide the name of a function, in this case 'sortByName'.
after that, you just add a function into your code (it doesn't really matter where you put it, even if it's at the bottom of the page):
function sortByName($categories, $b) {
return strcasecmp($categories["name"], $b["name"]);
}
Basically what this function does, is compairing your array with ...your array :) so it can sort it alfabetically by name- like you want it.
sthe 'strcasecmp' is to compare your strings against eachother to sort it. not that this is case non sensitive (strcmp will be case sensitive too). I assume you don't want it to check on uppercase and so on too, otherwise the result won't be what you wanted.
when you added that code, you can just print your array again:
echo "<pre>";
print_r($categories);
your result will be:
Array
(
[0] => Array
(
[id] => 18
[name] => aa
[children] => Array
(
)
)
[1] => Array
(
[id] => 12
[name] => Car
[children] => Array
(
[0] => Array
(
[id] => 14
[name] => volvo
)
)
[0] => Array
(
[0] => Array
(
[id] => 15
[name] => Mercedez-Benz
)
)
)
[2] => Array
(
[id] => 13
[name] => Manga
[children] => Array
(
[0] => Array
(
[id] => 16
[name] => Naruto
)
)
[0] => Array
(
[0] => Array
(
[id] => 17
[name] => Hunter X Hunter
)
)
)
I hope this is what you wanted. :-)

Categories