Organizing an array into a nested array with PHP - php

Does any on know how can I convert this
$events = array(
array("type" => "off-site", "title" => "aaa", "nid" => "11"),
array("type" => "off-site", "title" => "bbb", "nid" => "22"),
array("type" => "installation", "title" => "ccc", "nid" => "33"),
array("type" => "opening", "title" => "ddd", "nid" => "44"),
array("type" => "opening", "title" => "eee", "nid" => "55"),
array("type" => "opening", "title" => "fff", "nid" => "66")
);
into this
$events_processed = array(
"off-site" => array(
array(
"title" => "aaa",
"nid" => "11"
),
array(
"title" => "bbb",
"nid" => "22"
)
),
"installation" => array(
array(
"title" => "ccc",
"nid" => "33"
)
),
"opening" => array(
array(
"title" => "ddd",
"nid" => "44"
),
array(
"title" => "eee",
"nid" => "55"
),
array(
"title" => "fff",
"nid" => "66"
)
)
);
using php?
I've already tried to apply different methods from different posts here but with no success.
I need the array to be nested so I can reorder the array by "type".Hi

You can the code below, please note that your current output is not valid because you missed the array index ...
Example 1
$events_processed = array();
foreach($events as $options)
{
$events_processed[$options['type']][] = array("title"=>$options['title'],"nid"=>$options['nid']);
}
var_dump($events_processed);
OR
Example 2 (#dleiftah suggestion)
$defautKey = "type" ;
foreach($events as $options)
{
$type = $options[$defautKey] ;
unset($options[$defautKey]);
$events_processed[$type][] = $options;
}
var_dump($events_processed);
Both Result Would be Like this but number 2 is more flexible
array
'off-site' =>
array
0 =>
array
'title' => string 'aaa' (length=3)
'nid' => string '11' (length=2)
1 =>
array
'title' => string 'bbb' (length=3)
'nid' => string '22' (length=2)
'installation' =>
array
0 =>
array
'title' => string 'ccc' (length=3)
'nid' => string '33' (length=2)
'opening' =>
array
0 =>
array
'title' => string 'ddd' (length=3)
'nid' => string '44' (length=2)
1 =>
array
'title' => string 'eee' (length=3)
'nid' => string '55' (length=2)
2 =>
array
'title' => string 'fff' (length=3)
'nid' => string '66' (length=2)

Just loop through and reorganize ...
$result = array();
foreach($events as $event){
$key = $event['type'];
unset($event['type']);
$result[$key][] = $event;
}
print_r($result);

Here's what I did:
$array_processed = array();
foreach( $events as $evt){
$array_processed[$evt['type']][] = array('title'=>$evt['title'], 'nid'=>$evt['nid']);
}
print_r($array_processed);

There is no built in function that will do this. You will have to loop through this array and make a new array.
$events=array(contents-of-array);
$proc_events=array(
'off-site' => array(),
'installation' => array(),
'opening' => array()
);
foreach($events as $key => $value)
{
switch($value['type'])
{
case 'off-site':
$proc_events['offsite']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
case 'installation':
$proc_events['installation']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
case 'opening':
$proc_events['opening']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
}
}
The above should work.

The shortest code to do this should be:
foreach ($events as $event)
$events_processed[$event['type']][] = array('title' => $event['title'], 'nid' => $event['nid']);

Here is what I was able to do:
<?php
$events = array(
array("type" => "off-site", "title" => "aaa", "nid" => "11"),
array("type" => "off-site", "title" => "bbb", "nid" => "22"),
array("type" => "installation", "title" => "ccc", "nid" => "33"),
array("type" => "opening", "title" => "ddd", "nid" => "44"),
array("type" => "opening", "title" => "eee", "nid" => "55"),
array("type" => "opening", "title" => "fff", "nid" => "66")
);
foreach ($events as $event) {
$events_processed[$event['type']][] = array('title' => $event['title'],
'nid' => $event['nid']
);
}
echo '<pre>';
print_r($events_processed);
?>
This prints the following:
Array
(
[off-site] => Array
(
[0] => Array
(
[title] => aaa
[nid] => 11
)
[1] => Array
(
[title] => bbb
[nid] => 22
)
)
[installation] => Array
(
[0] => Array
(
[title] => ccc
[nid] => 33
)
)
[opening] => Array
(
[0] => Array
(
[title] => ddd
[nid] => 44
)
[1] => Array
(
[title] => eee
[nid] => 55
)
[2] => Array
(
[title] => fff
[nid] => 66
)
)
)

Related

How to sort multidimensional array in PHP

I have tried almost all suggestions online, and I really can't figure out how to sort this SESSION array.
I want it sorted by "itemname"..
I have and want this output, but I need the itemname to determine which item array come first.
Array
(
[person] => Array
(
[namex] => Array
(
[itema] => Array
(
[itemid] => 43
[itemname] => def
)
[itemc] => Array
(
[itemid] => 33
[itemname] => abc
)
[itemg] => Array
(
[itemid] => 29
[itemname] => ghi
)
)
[namey] => Array
(
[itemj] => Array
(
[itemid] => 12
[itemname] => abc
)
[iteme] => Array
(
[itemid] => 44
[itemname] => jkl
)
[itemr] => Array
(
[itemid] => 20
[itemname] => rst
)
)
)
)
So, "person" stays the same, but name, item, itemid and itemname is always different.
Can anyone help me sort this by itemname?
I need the array to be like this, so can't change it up.
Also.. I need to access it later in a foreach, so I can print out the items.
As pointed out in the comments to the question the desired output is not really defined. You'd have to give a specific definition of the output, without that we have to assume what you probably are looking for:
<?php
$data = [
"person" => [
"namex" => [
"itema" => [
"itemid" => 43,
"itemname" => "def"
],
"itemc" => [
"itemid" => 33,
"itemname" => "abc"
],
"itemg" => [
"itemid" => 29,
"itemname" => "ghi"
]
],
"namey" => [
"itemj" => [
"itemid" => 12,
"itemname" => "abc"
],
"iteme" => [
"itemid" => 44,
"itemname" => "jkl"
],
"itemr" => [
"itemid" => 20,
"itemname" => "rst"
]
]
]
];
foreach ($data["person"] as $personName => &$person) {
uasort($person, function($a, $b) {
return $a["itemname"] > $b["itemname"];
});
}
print_r($data);
The obvious output is:
Array
(
[person] => Array
(
[namex] => Array
(
[itemc] => Array
(
[itemid] => 33
[itemname] => abc
)
[itema] => Array
(
[itemid] => 43
[itemname] => def
)
[itemg] => Array
(
[itemid] => 29
[itemname] => ghi
)
)
[namey] => Array
(
[itemj] => Array
(
[itemid] => 12
[itemname] => abc
)
[iteme] => Array
(
[itemid] => 44
[itemname] => jkl
)
[itemr] => Array
(
[itemid] => 20
[itemname] => rst
)
)
)
)
Assuming the input from the example is represented via array as:
<?php
$array = [
'person' => [
'namex' => [
'itema' => [
'itemid' => 43,
'itemname' => 'def'
],
'itemb' => [
'itemid' => 33,
'itemname' => 'abc'
],
'itemc' => [
'itemid' => 29,
'itemname' => 'ghi'
],
],
'namey' => [
'itema' => [
'itemid' => 12,
'itemname' => 'abc'
],
'itemb' => [
'itemid' => 44,
'itemname' => 'jkl'
],
'itemc' => [
'itemid' => 20,
'itemname' => 'rst'
],
],
]
];
You could do use array_multisort in a loop:
$ids = [];
foreach($array as $key => $value) {
foreach ($value as $newKey => $value2) {
$ids[$newKey] = array_column($value2, 'itemname');
array_multisort($ids[$newKey], SORT_NATURAL, $array[$key][$newKey]);
}
}
This will output
array(1) {
'person' =>
array(2) {
'namex' =>
array(3) {
'itemb' =>
array(2) {
'itemid' =>
int(33)
'itemname' =>
string(3) "abc"
}
'itema' =>
array(2) {
'itemid' =>
int(43)
'itemname' =>
string(3) "def"
}
'itemc' =>
array(2) {
'itemid' =>
int(29)
'itemname' =>
string(3) "ghi"
}
}
'namey' =>
array(3) {
'itema' =>
array(2) {
'itemid' =>
int(12)
'itemname' =>
string(3) "abc"
}
'itemb' =>
array(2) {
'itemid' =>
int(44)
'itemname' =>
string(3) "jkl"
}
'itemc' =>
array(2) {
'itemid' =>
int(20)
'itemname' =>
string(3) "rst"
}
}
}
}

php array i have an array and i need to place some values in the array

I have an function called send message
function sendMessage(){
$content = array(
"en" => 'value1'
);
$headings = array(
"en" => 'value2'
);
$hashes_array = array();
fields = array(
'app_id' => "31fe2347-5f39-4d9f-2222-79bf542f00f9",
'included_segments' => array(
'All'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'headings' => $headings,
'url' => 'http://www.999999.in/view.php?id=[id]',
'chrome_web_image' => 'http://www.99999.in/admin/user_images/[userPic]',
);
And I have an array ready
Array(
[id] => 498
[value2] => యూట్యూబ్‌లో “భరత్ అనే నేను” అన్ కట్ సీన్లు..!
[value1] => కొరటాల శివ దర్శకత్వం లో సూ...
[value3] => 525722.jpg
)
Now just I need to place array values in function
Please help me on this I tried all echo values
Pass the array as an argument to the function, then access the elements.
function sendMessage($array) {
$content = array(
"en" => $array['value1']
);
$headings = array(
"en" => $array['value2']
);
$hashes_array = array();
$fields = array(
'app_id' => "31fe2347-5f39-4d9f-2222-79bf542f00f9",
'included_segments' => array(
'All'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'headings' => $headings,
'url' => 'http://www.999999.in/view.php?id=' . $array['id'],
'chrome_web_image' => 'http://www.99999.in/admin/user_images/' . $array['value3'],
);
print_r($fields);
}
DEMO
try like this
$valueArray = ['id' => 498, 'value2' => 'యూట్యూబ్‌లో “భరత్ అనే నేను” అన్ కట్ సీన్లు..!', 'value1' => 'కొరటాల శివ దర్శకత్వం లో సూ... ', 'value3' => '525722.jpg'];
output
Array
(
[id] => 498
[value2] => యూట్యూబ్‌లో “భరత్ అనే నేను” అన్ కట్ సీన్లు..!
[value1] => కొరటాల శివ దర్శకత్వం లో సూ...
[value3] => 525722.jpg
)
update your function with following code
function sendMessage($valueArray){
extract($valueArray);
$fields = array(
'app_id' => "31fe2347-5f39-4d9f-2222-79bf542f00f9",
'included_segments' => array('All' ),
'data' => array( "foo" => "bar" ),
'contents' => array( "en" => $value1 ),
'headings' => array( "en" => $value2 ),
'url' => 'http://www.999999.in/view.php?id=[id]',
'chrome_web_image' => 'http://www.99999.in/admin/user_images/[userPic]',
);
print_r($fields);
}
pass the array parameter to the function
sendMessage($valueArray);
output
Array
(
[app_id] => 31fe2347-5f39-4d9f-2222-79bf542f00f9
[included_segments] => Array
(
[0] => All
)
[data] => Array
(
[foo] => bar
)
[contents] => Array
(
[en] => కొరటాల శివ దర్శకత్వం లో సూ...
)
[headings] => Array
(
[en] => యూట్యూబ్‌లో “భరత్ అనే నేను” అన్ కట్ సీన్లు..!
)
[url] => http://www.999999.in/view.php?id=[id]
[chrome_web_image] => http://www.99999.in/admin/user_images/[userPic]
)

Compare multi-dimensional array and return missing keys in array

I have two multi-dimensional associative array ,
first we have
Array
(
[user_authentication] => Array
(
[api_user_id] => xxxxxxxxxxxxxxxxxxxxxxxx
[api_auth_token] => xxxxxxxxxxxxxxxxxxxxxx
)
[campaign_details] => Array
(
[campaign_name] => democampaign
[campaign_category] => appsGames
[campaign_sub_category] => Action
[campaign_type] => cpc
[campaign_start_date] => MM/DD/YYYY
[campaign_end_date] => MM/DD/YYYY
[campaign_start_time] => HH:mm
[campaign_end_time] => HH:mm
)
[campaign_budget_info] => Array
(
[campaign_daily_budget] => 0.2
[campaign_hourly_budget] => 0.3
[campaign_bid] => 0.1
[campaign_budget] => 1
)
[campaign_targetting_info] => Array
(
[campaign_os_type] => Apple
[country_code] => IN,AF,AG
[state_id] => Array
(
[IN] => 1,2,3
[AF] => 4,5,6
[AG] => 7,8,9
)
[carrier] => Array
(
[IN] => Tata,Aircel,RCOM,Vodafone,Airtel,Idea Cellular,Uninor,Dishnet,BSNL
[AF] =>
[AG] =>
)
[isp] =>
[device_targeting] => iphone,ipad
[conversion] =>
)
[campaign_creative_info] => Array
(
[campaign_domain] => abcd.com
[campaign_click_url] => http://url-to-redirect-users-to-after-they-click.com/
[campaign_banner_size] => URL640x1136
[campaign_banner_url] => http://imageurl.com/
[campaign_creative_type] => image
)
[campaign_black_list_white_list_info] => Array
(
[black_list_app_ids] => 5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54
[black_list_device_ids] => aaaaaaaa-bbbb-cccc-0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r
[black_list_ip_addresses] => 123.123.12.123,10.100.100.100
[white_list_app_ids] => 5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54
[white_list_device_ids] => aaaaaaaa-bbbb-cccc-0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r
[white_list_ip_addresses] => 123.123.12.123,10.100.100.100
)
)
and second one is which i have make to compare with
Array
(
[user_authentication] => Array
(
[api_user_id] => 1
[api_auth_token] => 1
)
[campaign_details] => Array
(
[campaign_name] => 1
[campaign_category] => 1
[campaign_sub_category] => 1
[campaign_type] => 1
[campaign_start_date] => 1
[campaign_end_date] => 1
[campaign_start_time] => 1
[campaign_end_time] => 1
)
[campaign_budget_info] => Array
(
[campaign_daily_budget] => 1
[campaign_hourly_budget] => 1
[campaign_bid] => 1
[campaign_budget] => 1
)
[campaign_targetting_info] => Array
(
[campaign_os_type] => 1
[country_code] => 1
[state_id] => Array
(
[IN] => 1
[AF] => 1
[AG] => 1
)
[carrier] => Array
(
[IN] => 1
[AF] => 1
[AG] => 1
)
[isp] => 1
[device_targeting] => 1
[conversion] => 1
)
[campaign_creative_info] => Array
(
[campaign_domain] => 1
[campaign_click_url] => 1
[campaign_banner_size] => 1
[campaign_banner_url] => 1
[campaign_creative_type] => 1
)
[campaign_black_list_white_list_info] => Array
(
[black_list_app_ids] => 1
[black_list_device_ids] => 1
[black_list_ip_addresses] => 1
[white_list_app_ids] => 1
[white_list_device_ids] => 1
[white_list_ip_addresses] => 1
)
)
we have to compare the array and find which key is missing in first array
i have tried this but not working
$comparemodel= array_diff_assoc($array1,$array2);
if($comparemodel==0){
echo "hello";
}
else{
$keys = array_keys($comparemodel);
for ($i = 0; $i < count($keys); $i++) {
$error_message[] = $keys[$i] . " is missing";
}
$model = array();
$errors = array("error_code" => 3042, "error_message" => $error_message);
$message = $error_message;
$status = 0;
$finalarray = array("modal" => $model, "errors" => $errors, "message" => $message, "status" => $status);
echo json_encode($finalarray);
}
its not working with this associative array but its working with simple array. what should i do for this.
thanks
try this code
<?php
$arr1=array("campaign_details" => array
(
"campaign_name" => "democampaign",
"campaign_category" => "appsGames",
"campaign_sub_category" => "Action",
"campaign_type" => "cpc",
"campaign_start_date" => "MM/DD/YYYY",
"campaign_end_date" => "MM/DD/YYYY",
"campaign_start_time" => "HH:mm",
"campaign_end_time" => "HH:mm"
),
"campaign_budget_info" => array
(
"campaign_daily_budget" => 0.2,
"campaign_hourly_budget" => 0.3,
"campaign_bid" => 0.1,
"campaign_budget" => 1,
),
"campaign_targetting_info" => array
(
"campaign_os_type" => "Apple",
"country_code" => "IN,AF,AG",
"state_id" => array
(
"IN" => "1,2,3",
"AF" => "4,5,6",
"AG" => "7,8,9"
),
"carrier" => Array
(
"IN" => "Tata,Aircel,RCOM,Vodafone,Airtel,Idea
Cellular,Uninor,Dishnet,BSNL",
"AF" => "",
"AG" => "",
),
"isp" => "",
"device_targeting" => "iphone,ipad",
"conversion" => "",
),
"campaign_creative_info" => array
(
"campaign_domain" => "abcd.com",
"campaign_click_url" => "http://url-to-redirect-users-to-after-
they-click.com/",
"campaign_banner_size" => "URL640x1136",
"campaign_banner_url" => "http://imageurl.com/",
"campaign_creative_type" => "image",
),
"campaign_black_list_white_list_info" => array
(
"black_list_app_ids" =>
"5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54",
"black_list_device_ids" => "aaaaaaaa-bbbb-cccc-
0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r",
"black_list_ip_addresses" => "123.123.12.123,10.100.100.100",
"white_list_app_ids" =>
"5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54",
"white_list_device_ids" => "aaaaaaaa-bbbb-cccc-
0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r",
"white_list_ip_addresses" => "123.123.12.123,10.100.100.100",
)
);
$arr2=array("campaign_details" =>array
(
"campaign_name" => 1,
"campaign_category" => 1,
"campaign_sub_category" => 1,
"campaign_type" => 1,
"campaign_start_date" => 1,
"campaign_end_date" => 1,
"campaign_start_time" => 1,
"campaign_end_time" => 1
),
"campaign_budget_info" => array
(
"campaign_daily_budget" => 1,
"campaign_hourly_budget" => 1,
"campaign_bid" => 1,
"campaign_budget" => 1,
),
"campaign_targetting_info" => array
(
"campaign_os_type" => 1,
"country_code" => 1,
"state_id" => array
(
"IN" => 1,
"AF" => 1,
"AG" => 1,
),
"carrier" => array
(
"IN" => 1,
"AF" => 1,
"AG" => 1,
),
"isp" => 1,
"device_targeting" => 1,
"conversion" => 1,
),
"campaign_creative_info" =>array
(
"campaign_domain" => 1,
"campaign_click_url" => 1,
"campaign_banner_size" => 1,
"campaign_banner_url" => 1,
"campaign_creative_type" => 1,
),
"campaign_black_list_white_list_info" => array
(
"black_list_app_ids" => 1,
"black_list_device_ids" => 1,
"black_list_ip_addresses" => 1,
"white_list_app_ids" => 1,
"white_list_device_ids" => 1,
"white_list_ip_addresses" => 1,
)
);
function array_keys_multi(array $array)
{
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($array[$key])) {
$keys = array_merge($keys, array_keys_multi($array[$key]));
}
}
return $keys;
}
$resArr=array();
$a=array_keys_multi($arr1);
$b=array_keys_multi($arr2);
$c=array_diff($a,$b);
if(count($c) > 0){
echo "There is differnce<br/>";
echo "<pre>";
print_r($c);
}else
echo "There is no differnce<br/>";
?>

PHP: Convert an array with a path attribute to a tree structure

Lets say, I have the following array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
);
As you can see, its a multidimensional array with 3 properites in earch 2nd level array: id, name and path. The path is a path structure based on the parent-id of its parent. For example, Germany (id=2) has belongs to Europe, so the path is "/1/" (ID 1 = Europe) and Berlin in Germany has the path "/1/2/" which means "/Europe/Germany/"
Now, I am trying to create a tree-array out of this, which should somehow look like:
$result = array(
1 => array(
"id" => 1,
"name" => "Europe",
"path" => "/",
"childs" => array(
2 => array(
"id" => 2,
"name" => "Germany",
"path" => "/1/",
"childs" => array(
4 => array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
5 => array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
)
),
3 => array(
"id" => 3,
"name" => "France",
"path" => "/1/"
)
)
)
);
I have already tried to create a function with internal references, but this didn't works for me:
public static function pathToTree($items) {
$array = array();
$result = array();
foreach($items AS $res) {
$ids = explode("/", ltrim($res["path"] . $res["id"], "/"));
$count = count($ids);
$tmp = &$result;
foreach( $ids AS $id) {
if($count == 1) {
$tmp = $res;
$tmp["childs"] = array();
$tmp = &$tmp["childs"];
}
else {
$tmp[$id] = array(
"childs" => array()
);
$tmp = &$tmp[$id]["childs"];
}
$count--;
}
}
return $array;
}
Ok, I think I just found a solution:
function pathToTree($array){
$tree = array();
foreach($array AS $item) {
$pathIds = explode("/", ltrim($item["path"], "/") . $item["id"]);
$current = &$tree;
foreach($pathIds AS $id) {
if(!isset($current["childs"][$id])) $current["childs"][$id] = array();
$current = &$current["childs"][$id];
if($id == $item["id"]) {
$current = $item;
}
}
}
return $tree["childs"];
}
This is a dynamice solution for 1-n depth. Look at my example at http://ideone.com/gn0XLp . Here I tested it with some level:
Continent
Country
City
City-District
City-Subdistrict
City Sub-Sub-District
I've created a recursive function:
// The array
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "India",
"path" => "/6/"
),
array(
"id" => 7,
"name" => "Mumbai",
"path" => "/6/7"
),
array(
"id" => 8,
"name" => "Delhi",
"path" => "/6/7"
),
);
// The recursive function
function createTree($input, &$result = array(), $key = null) {
if ($key == "id") {
$result["temp"]["id"] = $input;
}
if ($key == "name") {
$result["temp"]["name"] = $input;
}
if ($key == "path") {
$result["temp"]["path"] = $input;
$levels = is_string($input) ? array_values(array_filter(explode('/', $input))) : null;
if ($input == "/") {
$result[$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 1) {
$result[$levels[0]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 2) {
$result[$levels[0]]["childs"][$levels[1]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
unset($result["temp"]);
}
if (is_array($input)) {
foreach($input as $key => $value) {
createTree($value, $result, $key);
}
}
return $result;
}
// The result
array (
1 =>
array (
'id' => 1,
'name' => 'Europe',
'path' => '/',
'childs' =>
array (
2 =>
array (
'id' => 2,
'name' => 'Germany',
'path' => '/1/',
'childs' =>
array (
4 =>
array (
'id' => 4,
'name' => 'Berlin',
'path' => '/1/2/',
),
5 =>
array (
'id' => 5,
'name' => 'Munich',
'path' => '/1/2/',
),
),
),
3 =>
array (
'id' => 3,
'name' => 'France',
'path' => '/1/',
),
),
),
6 =>
array (
'id' => 6,
'name' => 'Asia',
'path' => '/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'India',
'path' => '/6/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'Mumbai',
'path' => '/6/7',
),
8 =>
array (
'id' => 8,
'name' => 'Delhi',
'path' => '/6/7',
),
),
),
),
),
)
As I said in the comment, you need at least three loops to achieve your goals. Here's the function:
function pathToTree($array){
$tree = Array();
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 1)
$tree[$array[$i]["id"]] = $array[$i];
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 2){
$num = (int)str_replace("/","",$array[$i]["path"]);
$tree[$num]["childs"][$array[$i]["id"]] = $array[$i];
}
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 3){
$num = explode("/", $array[$i]["path"]);
$tree[$num[1]]["childs"][$num[2]]["childs"][$array[$i]["id"]] = $array[$i];
}
}
return $tree;
}
Example:
Consider this array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "China",
"path" => "/6/"
),
array(
"id" => 8,
"name" => "Bangladesh",
"path" => "/6/"
),
array(
"id" => 9,
"name" => "Beijing",
"path" => "/6/7/"
),
array(
"id" => 10,
"name" => "Dhaka",
"path" => "/6/8/"
)
);
if I ran this code:
print_r(pathToTree($array));
the output will be:
Array
(
[1] => Array
(
[id] => 1
[name] => Europe
[path] => /
[childs] => Array
(
[2] => Array
(
[id] => 2
[name] => Germany
[path] => /1/
[childs] => Array
(
[4] => Array
(
[id] => 4
[name] => Berlin
[path] => /1/2/
)
[5] => Array
(
[id] => 5
[name] => Munich
[path] => /1/2/
)
)
)
[3] => Array
(
[id] => 3
[name] => France
[path] => /1/
)
)
)
[6] => Array
(
[id] => 6
[name] => Asia
[path] => /
[childs] => Array
(
[7] => Array
(
[id] => 7
[name] => China
[path] => /6/
[childs] => Array
(
[9] => Array
(
[id] => 9
[name] => Beijing
[path] => /6/7/
)
)
)
[8] => Array
(
[id] => 8
[name] => Bangladesh
[path] => /6/
[childs] => Array
(
[10] => Array
(
[id] => 10
[name] => Dhaka
[path] => /6/8/
)
)
)
)
)
)
Here's the phpfiddle link in case you might try it yourself.

How do I group same array

Example my array
Array (
[0] => Array
(
[product_name] => T-Shirt
[product_id] => 231
[user_id] => 22977
)
[1] => Array
(
[product_name] => Shirt
[product_id] => 220
[user_id] => 22977
)
[2] => Array
(
[product_name] => T-Shirt
[product_id] => 226
[user_id] => 16916
)
[3] => Array
(
[product_name] => Bags
[product_id] => 230
[user_id] => 16916
)
[4] => Array
(
[product_name] => Hats
[product_id] => 233
[user_id] => 22977
)
)
How to generate this array to be
User-Id: 22977
1/ Hats
2/ Shirt
3/ T-Shirt
User-Id: 16916
1/ Bags
2/ T-Shirt
$a = array();
$a[] = array("product_name" => "T-Shirt", "product_id" => 231, "user_id" => 22977);
$a[] = array("product_name" => "Shirt", "product_id" => 220, "user_id" => 22977);
$a[] = array("product_name" => "T-Shirt", "product_id" => 226, "user_id" => 16916);
$a[] = array("product_name" => "Bags", "product_id" => 230, "user_id" => 16916);
$a[] = array("product_name" => "Hats", "product_id" => 233, "user_id" => 22977);
$return = array();
foreach ($a as $key => $value) {
$return[$value["user_id"]][] = $value["product_name"];
}
foreach ($return as $key => $value) {
echo "User-Id: " . $key . "\r\n";
$i = 0;
foreach ($value as $val) {
echo ++$i . "/ " . $val . "\r\n";
}
}
Output will be:
User-Id: 22977
1/ T-Shirt
2/ Shirt
3/ Hats
User-Id: 16916
1/ T-Shirt
2/ Bags
You can use this:
$testarray = array(
array(
"product_name" => 'T-Shirt',
"product_id" => 231,
"user_id" => 22977),
array
(
"product_name" => 'Shirt',
"product_id" => 220,
"user_id" => 22977,
),
array
(
"product_name" => 'T-Shirt',
"product_id" => 226,
"user_id" => 16916,
),
array
(
"product_name" => 'Bags',
"product_id" => 230,
"user_id" => 16916,
),
array
(
"product_name" => 'Hats',
"product_id" => 233,
"user_id" => 22977,
),
);
$newArray = array();
foreach ($testarray as $subArray) {
$newArray[$subArray["user_id"]][] = $subArray['product_name'];
}
var_dump ($newArray);
Output is:
array
22977 =>
array
0 => string 'T-Shirt' (length=7)
1 => string 'Shirt' (length=5)
2 => string 'Hats' (length=4)
16916 =>
array
0 => string 'T-Shirt' (length=7)
1 => string 'Bags' (length=4)
<?php
//initialize array
$array = Array(
'0' => Array
(
'product_name' => 'T-Shirt',
'product_id' => 231,
'user_id' => 22977
),
'1' => Array
(
'product_name' => 'Shirt',
'product_id' => 220,
'user_id' => 22977
),
'2' => Array
(
'product_name' => 'T-Shirt',
'product_id' => 226,
'user_id' => 16916
),
'3' => Array
(
'product_name' => 'Bags',
'product_id' => 230,
'user_id' => 16916
),
'4' => Array
(
'product_name' => 'Hats',
'product_id' => 233,
'user_id' => 22977
)
);
//result will be here
$result = array();
foreach ($array as $key => $value) {
//check if we have keys group or names to avoid errors
if(!isset($value['user_id']) || !isset($value['product_name']))
continue;
//make a key in result array if its not exist
if(!isset($result[$value['user_id']]))
{
$result[$value['user_id']] = array($value['product_name']);
}
else
{
//add a values to key if it exists
$result[$value['user_id']][] = $value['product_name'];
//filter same values
$result[$value['user_id']] = array_values(array_unique($result[$value['user_id']]));
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>

Categories