Merging two multi-dimensional arrays using key and adding values - php

I want to merge two array's using key(product_id) and adding that values(usage).
Array 1
Array
(
[0] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
[1] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 1
[product_id] => 14
)
)
Array 2
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 2
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
)
I need an out put like this merging and adding usage values.
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 2
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 3
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
[5] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
)
This is my code for creating arrays
foreach($query->rows as $product){
$top_products[]=array(
'name'=>$product['name'],
'usage'=>$product['pusage'],
'product_id'=>$product['product_id']
);
}
foreach($query_2->rows as $product){
$top_point_products[]=array(
'name'=>$product['name'],
'usage'=>$product['p_usage'],
'product_id'=>$product['product_id']
);
}

$first =array(
array(
"name" => "Reschedule A Service",
"usage" => 1,
"product_id" => 8
),
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Each Calendar Event",
"usage" => 1,
"product_id" => 14
)
);
$second =array(
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Schedule A Service",
"usage" => 3,
"product_id" => 11
),
array(
"name" => "Each Calendar Event",
"usage" => 2,
"product_id" => 14
),
array(
"name" => "Sales Performance Dashboard",
"usage" => 2,
"product_id" => 30
),
array(
"name" => "Quote",
"usage" => 1,
"product_id" => 32
)
);
$result = array_unique(array_merge($first,$second), SORT_REGULAR);
Use array_unique & array_merge

Use the array_merge function, like this:
$C = array_merge($A, $B);
print_r($C);
Read manual Array merge

try this code
<?php
$array1=array
(
0 => array(
'name' => "Reschedule A Service",
'usage' => 1,
'product_id' => 8
),
1 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 2,
'product_id' => 14
)
);
$array2=array
(
0 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
1 => Array
(
'name' => "Schedule A Service",
'usage' => 3,
'product_id' => 11
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 5,
'product_id' => 14
),
3 => Array
(
'name' => "Sales Performance Dashboard",
'usage' => 2,
'product_id' => 30
),
4 => Array
(
'name' => "Quote",
'usage' => 1,
'product_id' => 32
)
);
$product_id1=array_column($array1, 'product_id');
$product_id2=array_column($array2, 'product_id');
$new=array_intersect($product_id1,$product_id2);
foreach ($new as $key => $value) {
if(in_array($new[$key],$product_id2)){
$array2[array_search($new[$key],$product_id2)]['usage']+=$array1[$key]['usage'];
}
}
$new1=array_diff($product_id1,$product_id2);
foreach ($new1 as $key => $value) {
$array2[]=$array1[$key];
}
foreach ($array2 as $key => $value) {
echo "[".$key."]=><br>";
foreach ($value as $key1 => $value1) {
echo "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
echo "[".$key1."]=>".$value1."<br>";
}
echo "<br>";
}
?>
output
[0]=>
[name]=>Adding An Image
[usage]=>2
[product_id]=>5
[1]=>
[name]=>Schedule A Service
[usage]=>3
[product_id]=>11
[2]=>
[name]=>Each Calendar Event
[usage]=>7
[product_id]=>14
[3]=>
[name]=>Sales Performance Dashboard
[usage]=>2
[product_id]=>30
[4]=>
[name]=>Quote
[usage]=>1
[product_id]=>32
[5]=>
[name]=>Reschedule A Service
[usage]=>1
[product_id]=>8

Use array_merge and a simple foreach loop to check your condition and update the usagevalues.
See below
$result = array_merge($arrArray1, $arrArray2);
$result2 = array();
foreach($result as $key => $value){
if(array_key_exists($value['product_id'], $result2)){
$result2[$value['product_id']]['usage'] += $value['usage'];
} else{
$result2[$value['product_id']] = $value;
}
}
print_r($result2);
If you want to reset your resultant array indexes use array_merge again like this
$result2 = array_merge($result2);
Hope this will help

Related

Removing first array of multidimensional array

I want to remove the first.. how to say that outside of the array and left inside array of a multidimension array. I couldn't found out the solution.. someone knows how to do it??
This is my code. I assign a array and i try to put into another array like this.
$final_sku = array();
foreach($skus as $sku){
foreach($sku as $key => $s){
$final_sku[] = array('Sku' => $s);
}
}
$newArray = array(
"Product" => array(
"PrimaryCategory" => "1",
"AssociatedSku" => "12",
"Attributes" => array(
),
"Skus" => $final_sku
)
);
And this is the $final_sku output be like.
[0] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
)
[1] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
)
I want the output be like this.
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
UPDATE: I want to pass the array and convert to xml. So the array key would be duplicated.
It does not make sense to have the same array of 2 members under the same key.
If you want to access one of them, what will be its uniqueness over the other?
The logical solution is
[sku] => [
0 => [first sku data....],
1 => [sku data....],
]

Php check and replace if value exist in multi array?

Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);

codeigniter insert multi-dimensional array to the database

Hello I have this multi dimensional array which needs to be inserted to the database table.
so far I have come up with this solution which don't work fully. I have a form that support dynamic fields many dynamic fields. I want to save those dynamically created fields using this function. First I had been able to create a loop to format the data.
I used this loop to format the data
$url = str_replace(' ','-',strtolower($this->input->post('title')));
$data = ['business' => [
'title' => $this->input->post('title'),
'URL' => $url,
'category' => $this->input->post('category'),
'region' => $this->input->post('region')
],
'description_' => [
'text' => $this->input->post('description'),
],
'logo_' => [
'blob' => $this->input->post('logo'),
]];
$nyingi = [ 'location_' => ['text' => 'loc_txt','priority' => 'loc_order'],
'photo_' => ['path' => 'p_txt'],
'video_' => ['path' => 'v_txt'],
'product_' => ['p_id' => 'pt_q', 'text' => 'pt_txt', 'expire' => 'pt_xpr', 'title' => 'pt_tt'],
'service_' => ['p_id' => 'st_q', 'text' => 'st_txt', 'expire' => 'st_xpr', 'title' => 'st_tt'],
'hours_' => ['time1' => 't1', 'time2' => 't2', 'type' => 'tt'],
'map_' => ['text' => 'm_txt']
];
foreach($nyingi as $ins => $vl){
foreach($vl as $fld => $box){
$uwazi = $this->input->post($box);
if(is_array($uwazi) && 1<count($uwazi)){
foreach($uwazi as $bb){
$one[$ins][$fld][] = $bb;
}
} elseif(is_array($uwazi) && 1==count($uwazi)) {
print_r($uwazi);
}
}
}
for($g=0;$g<count($one);$g++){
for($h=0;$h<count($one[$g]);$h++){
for($z=0;$z<count($one[$g][$h]);$z++){
//if(array_key_exists($one[$g][$h+1], $one)){
print $one[$g][$h][$z+1];
//}
}
}
}
$data = array_merge($data, $one);
The output of the above code
[location_] => Array
(
[text] => Array
(
[0] => Lemara Main Office
[1] => Themi branch
[2] => Sinoni branch
)
[priority] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[photo_] => Array
(
[path] => Array
(
[0] => lemaraphoto.png
[1] => themiphoto.png
[2] => sinoniphoto.png
)
)
[video_] => Array
(
[path] => Array
(
[0] => lemaravideo.mp4
[1] => themivideo.mp4
[2] => sinonivideo.mp4
)
)
[product_] => Array
(
[p_id] => Array
(
[0] => product photo
[1] => product 3 photo
[2] => Product 2 photo
)
[text] => Array
(
[0] => product desc
[1] => product 3 desc
[2] => product 2 desc
)
[expire] => Array
(
[0] => product expire
[1] => product 3 expire
[2] => Product 2 expire
)
[title] => Array
(
[0] => product
[1] => Product 3
[2] => Product 2
)
)
[service_] => Array
(
[p_id] => Array
(
[0] => Service 2 photo
[1] => service 3 photo
[2] => service photo
)
[text] => Array
(
[0] => service 2 desc
[1] => service 3 desc
[2] => service desc
)
[expire] => Array
(
[0] => Service 2 expire
[1] => service 3 expire
[2] => service expire
)
[title] => Array
(
[0] => Service 2
[1] => service 3
[2] => service
)
)
)
I have this add_bz function
function add_bz($data){
$this->db->trans_start(); $er=0;
foreach($data as $table => $sql){
if($table==="business"){
$this->db->insert($table, $sql);
$id = $this->db->insert_id();
} else {
array_merge($sql, array('idd' => $id));
$this->db->insert($table, $sql);}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;}
return TRUE;
}
That function allows me to insert the data in this format only.
[[business] => Array
(
[title] => Email Marketing
[URL] => email-marketing
[category] => 3
[region] => 2
)
[description_] => Array
(
[text] => Some desc
)
[logo_] => Array
(
[blob] => mainlogo.png
)
]
as business, decription_, logo_ are db tables where title, URL, category, region, text, blob are the db columns to the corresponding tables and the rest is data that goes to those columns.
How I want it to works. For example in location_
I want to the array to change into my working format or something else that will work like this
location_ => ['text' => [[0] => 'Lemara Main Office'],
'priority' => [[0] => '1']
]
location_ => ['text' => [[1] => 'Themi Office'],
'priority' => [[1] => '2']
]
location_ => ['text' => [[2] => 'Sinoni Office'],
'priority' => [[2] => '3']
]
or like this
location_ => [0 => [['text' => 'Lemara Main Office'],
['priority' => '1']
],
1 => [['text' => 'Themi Main Office'],
['priority' => '2']
],
2 => [['text' => 'Sinoni Main Office'],
['priority' => '3']
]
],
And also support many columns not just the two.
Any help is deeply appreciated as I have been struggling for days to make this work. Thanks in advance.
I would suggest you convert your array to JSON String then insert it to DB as text.
JSON would handle your multidimentional data so well,
To convert your array to JSON : http://php.net/manual/en/function.json-encode.php
To convert your JSON to Array : http://php.net/manual/en/function.json-decode.php

Create new array depending on key

My array is like that:
Array
(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
)
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
[2] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[3] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
I want to change that array like that depending on key['type']. If array key['type'] are same, I want to change array like that:
Array
(
[car] => Array(
[0]=>Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
),
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
),
[train]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[cruise]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
)
)
what I mean is that if key['type'] is car, I want to create car array or if the type is train I want to create train array or if the type is cruise I want to create cruise array. I don't know how to loop the array. Anyone please help me. Thanks a lot!
Here's a simple way to do it: loop over the data, and just append to the subarray matching the type value:
// starting data
$starting_array = array (
0 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 1,
'tran_name' => 'private',
'tran_image' => '1251961905A1.jpg',
'type' => 'car',
'troute_id' => 10
),
1 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 2,
'tran_name' => 'express',
'tran_image' => 'bus3.jpg',
'type' => 'car',
'troute_id' => 13
),
2 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 3,
'tran_name' => 'MyanmarTrain',
'tran_image' => 'Burma-Gorteikviaduct.jpg',
'type' => 'train',
'troute_id' => 16
),
3 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 4,
'tran_name' => 'Ayeyarwaddy Cruise',
'tran_image' => 'boat-ChutzpahToo1.jpg',
'type' => 'cruise',
'troute_id' => 22
)
);
// initialize the result array
$result = array();
// loop over the starting array
foreach($starting_array as $entry) {
// make sure the result array has a key matching this item's type
if(!array_key_exists($entry['type'], $result)) {
$result[ $entry['type'] ] = array();
}
// add this item to the result array
$result[ $entry['type'] ][] = $entry;
}
// this is just for testing, so you can verify the output matches your desired result
echo "<pre>";
var_dump($result);
echo "</pre>";
Try this:
<?php
$tempArr = Array
(
Array(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 1,
"tran_name" => "private",
"tran_image" => "1251961905A1.jpg",
"type" => "car",
"troute_id" => 10
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 2,
"tran_name" => "express",
"tran_image" => "bus3.jpg",
"type" => "car",
"troute_id" => 13
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 3,
"tran_name" => "MyanmarTrain",
"tran_image" => "Burma-Gorteikviaduct.jpg",
"type" => "train",
"troute_id" => 16
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 4,
"tran_name" => "Ayeyarwaddy Cruise",
"tran_image" => "boat-ChutzpahToo1.jpg",
"type" => "cruise",
"troute_id" => 22
)
);
$resultArr = array();
foreach($tempArr as $tempKey=>$temp)
{
if(!array_key_exists($temp['type'], $resultArr))
{
$resultArr[$temp['type']] = array();
}
$resultArr[$temp['type']][] = $temp;
}
echo '<pre>';
print_r($resultArr);
?>
This is working fine .....

Swap array Item with condition

I have the situation to swap array with condition.My array is plotted bellow.
pid => like primary key in mysql so it may loose it order
type=> type indicates, product type.array having 3 type of products.
Name=> Simply indicates product name
First I tried solution in mysql, But I didn't got any good sign.Some of them suggest me array swapping is better one. But I don't know How to get this one.
My problem
I am having list of items.When i listing products, type 3(mater) should not come at 5,10,15
(i.e modules of 5 ) positions.If it does my design getting collapse.
Screen Shot explanation
Perfect placement
Collapsed design
So i want to make sure type 3(master) never comes at mod of 5 position.How can i do this
Help me
My previous try in mysql here
Array
(
[0] => Array
(
[pid] => 1
[type] => 1
[name] => A
)
[1] => Array
(
[pid] => 2
[type] => 1
[name] => B
)
[2] => Array
(
[pid] => 3
[type] => 2
[name] => D
)
[3] => Array
(
[pid] => 4
[type] => 3
[name] => E(master)
)
[4] => Array
(
[pid] => 5
[type] => 3
[name] => f(sub)
)
[5] => Array
(
[pid] => 6
[type] => 1
[name] => A1
)
[6] => Array
(
[pid] => 7
[type] => 2
[name] => B1
)
[7] => Array
(
[pid] => 8
[type] => 1
[name] => C1
)
[8] => Array
(
[pid] => 9
[type] => 2
[name] => D1
)
[9] => Array
(
[pid] => 10
[type] => 3
[name] => E1(master)
)
[10] => Array
(
[pid] => 11
[type] => 3
[name] => A2(sub)
)
[11] => Array
(
[pid] => 12
[type] => 2
[name] => B2
)
[12] => Array
(
[pid] => 13
[type] => 1
[name] => C2
)
[13] => Array
(
[pid] => 14
[type] => 2
[name] => D2
)
[14] => Array
(
[pid] => 15
[type] => 1
[name] => E2
)
)
Thanks in advance
I gave it a try, the following code should do the trick. What I recommend is that you split up a block in the several subparts that define a block. Furthermore, it's not very DRY code, but it will give you an idea:
<?php
$grid = array(); $blocks = array();
$blocks[] = array(array("pid" => 1, "type" => 1, "name" => "A"));
$blocks[] = array(array("pid" => 2, "type" => 1, "name" => "B"));
$blocks[] = array(array("pid" => 3, "type" => 2, "name" => "D"));
$blocks[] = array(array("pid" => 4, "type" => 3, "name" => "E(master)"), array("pid" => 5, "type" => 3, "name" => "F (sub)"));
$blocks[] = array(array("pid" => 6, "type" => 1, "name" => "A1"));
$blocks[] = array(array("pid" => 7, "type" => 2, "name" => "B1"));
$blocks[] = array(array("pid" => 8, "type" => 1, "name" => "C1"));
$blocks[] = array(array("pid" => 9, "type" => 2, "name" => "D1"));
$blocks[] = array(array("pid" => 10, "type" => 3, "name" => "E1 (master)"), array("pid" => 11, "type" => 3, "name" => "A2 (sub)"));
$blocks[] = array(array("pid" => 12, "type" => 2, "name" => "B2"));
$blocks[] = array(array("pid" => 13, "type" => 1, "name" => "C2"));
$blocks[] = array(array("pid" => 14, "type" => 2, "name" => "D2"));
$blocks[] = array(array("pid" => 14, "type" => 1, "name" => "E2"));
$current_row = 0;
for ($n=0;$n < count($blocks);$n++) {
//Check if current row exists in grid
if (!isset($grid[$current_row]))
{
//Create new empty row in grid
$grid[$current_row] = array();
}
//check if current block fits
if (count($grid[$current_row]) + count($blocks[$n]) > 5)
{
// Block doesn't fit: Search for block that fits
for ($i=$n;$i < count($blocks);$i++)
{
if (count($grid[$current_row]) + count($blocks[$i]) <= 5)
{
//place parts in block on current row
foreach ($blocks[$i] as $part)
{
$grid[$current_row][] = $part;
}
//unset block from queue
unset($blocks[$i]);
}
}
//place current block on new row
$current_row++;
}
//place parts in block in grid
foreach ($blocks[$n] as $part)
{
$grid[$current_row][] = $part;
}
}
print_r($grid);
?>

Categories