Convert array to multidimensional array PHP - php

I have converted xml string into php array. But the requirement is something different. Following is an array which is created using XML string by following
$xml = simplexml_load_string($mystin, "SimpleXMLElement",
LIBXML_NOCDATA); $json = json_encode($xml); $array =
json_decode($json,TRUE);
Array
(
[0] => Array
(
[data] => Array
(
[0] => Array
(
[attribute_set] => default
[description] => productdescription
[is_in_stock] => 1
[meta_description] => Product meta description
[meta_keyword] => Product meta keyword
[meta_title] => Product meta title
[name] => myproduct6
[price] => 100
[qty] => 1000
[re_skus] => sdfefwef
[short_description] => this is a short descriptio
[sku] => myproduct_surabhi7
[status] => 1
[store] => admin
[tax_class_id] => 4
[type] => simple
[url_key] => my-product
[url_path] => my-product.html
[visibility] => 4
[weight] => 10
)
[1] => Array
(
[attribute_set] => default
[description] => productdescription
[is_in_stock] => 1
[meta_description] => Product meta description
[meta_keyword] => Product meta keyword
[meta_title] => Product meta title
[name] => myproduct6
[price] => 100
[qty] => 1000
[re_skus] => sdfefwef
[short_description] => this is a short descriptio
[sku] => myproduct_surabhi7
[status] => 1
[store] => admin
[tax_class_id] => 4
[type] => simple
[url_key] => my-product
[url_path] => my-product.html
[visibility] => 4
[weight] => 10
)
)
)
)
I need the above array as following array:
Array
(
[0] => Array
(
[0] => Array
(
[name] => Product1
[sku] => Product1
[description] => Product description
[short_description] => Product short description
[weight] => 10
[status] => 1
[url_key] => wat12
[url_path] => wat12.html
[visibility] => 4
[price] => 100
[tax_class_id] => 4
[meta_title] => Product meta title
[meta_keyword] => Product meta keyword
[meta_description] => Product meta description
[store] => admin
[attribute_set] => default
[type] => simple
[is_in_stock] => 1
[color] => Orange
[re_skus] => Testsimple2,Testsimple1
)
)
[1] => Array
(
[1] => Array
(
[name] => Product2
[sku] => Product2
[description] => Product description
[short_description] => Product short description
[weight] => 10
[status] => 1
[url_key] => wat12
[url_path] => wat12.html
[visibility] => 4
[price] => 100
[tax_class_id] => 4
[meta_title] => Product meta title
[meta_keyword] => Product meta keyword
[meta_description] => Product meta description
[store] => admin
[attribute_set] => default
[type] => simple
[is_in_stock] => 1
[color] => Orange
[re_skus] => Testsimple2,Testsimple1
)
)
)

Try this may be it help
$array = array(
0 => array(
'data' => array(0 => array('abc2' => 1, 'adsg' =>2),1=>array('abc' => 1, 'adsg4' =>2)))
);
$new_data = array();
foreach ($array as $row)
{
for($i=0; $i<count($row['data']); $i++){
$newArray = array();
$newArray[$i] = $row['data'][$i];
$new_data[] = $newArray;
}
}
print_r($new_data);

Have a look at this example:
$array = array(
98 => array(
'City' => 'Caracas',
'Country' => 'Venezuela',
'Continent' => 'Latin America',
),
99 => array(
'City' => 'Cairo',
'Country' => 'Egypt',
'Continent' => 'Middle East',
),
105 => array(
'City' => 'Abu Dhabi',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
106 => array(
'City' => 'Dubai',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
107 => array(
'City' => 'Montreal',
'Country' => 'Canada',
'Continent' => 'North America',
)
);
$newArray = array();
foreach ($array as $row)
{
$newArray[$row['Continent']][$row['Country']][] = $row['City'];
}
print_r($newArray);

I got idea from Keval's answer. After doing a small change, it is working like charm.
$new_data = array();
foreach ($array as $row)
{
for($i=0; $i<count($row); $i++){
$newArray = array();
$newArray[$i] = $row[$i];
$new_data[] = $newArray;
}
}
print_r($new_data);

Related

Merge array by id and sum amount

I'm trying to merge and calc only by choosen key. For example I have the following array:
$array = array();
$array['Fruit'][] = ['id' => 17, 'name' => 'seasonal fruit', 'type' => 'Fruit', 'measurement' => '', 'amount' => 2];
$array['Fruit'][] = ['id' => 17, 'name' => 'seasonal fruit', 'type' => 'Fruit', 'measurement' => '', 'amount' => 1];
$array['protein'][] = ['id' => 16, 'name' => 'soy yogurt', 'type' => 'protein', 'measurement' => '', 'amount' => 2];
$array['protein'][] = ['id' => 18, 'name' => 'oilseed', 'type' => 'protein', 'measurement' => 'grip', 'amount' => 2];
$array['protein'][] = ['id' => 18, 'name' => 'oilseed', 'type' => 'protein', 'measurement' => 'grip', 'amount' => 1];
$array['lipid'][] = ['id' => 19, 'name' => 'coconut powder', 'type' => 'lipid', 'measurement' => 'Tablespoon', 'amount' => 2];
$array['lipid'][] = ['id' => 20, 'name' => 'chocolate powder', 'type' => 'lipid', 'measurement' => 'Tablespoon', 'amount' => 2];
$array['lipid'][] = ['id' => 38, 'name' => 'chocolate square', 'type' => 'lipid', 'measurement' => '', 'amount' => 1];
Final output should look like this :
Array (
[0] => Array (
[id] => 17
[name] => seasonal fruit
[type] => Fruit
[measurement] =>
[amount] => 3
)
[1] => Array (
[id] => 16
[name] => soy yogurt
[type] => protein
[measurement] =>
[amount] => 2
)
[2] => Array (
[id] => 18
[name] => oilseed
[type] => protein
[measurement] => grip
[amount] => 3
)
[3] => Array (
[id] => 19
[name] => coconut powder
[type] => lipid
[measurement] => Tablespoon
[amount] => 2
)
[4] => Array (
[id] => 20
[name] => chocolate powder
[type] => lipid
[measurement] => Tablespoon
[amount] => 2
)
[5] => Array (
[id] => 38
[name] => chocolate square
[type] => lipid
[measurement] =>
[amount] => 1
)
)
I tried the following :
$courses = [];
foreach ($array as $key => $item) {
if (!key_exists($key, $courses)) {
$courses[$key] = [];
}
foreach ($item as $row) {
$id = $row['id'];
if (!key_exists($id, $courses[$key])) {
$courses[$key][$id] = $row;
continue;
}
$r = &$courses[$key][$id];
$r['amount'] += $row['amount'];
}
}
Output:
Array (
[Fruit] => Array (
[17] => Array (
[id] => 17
[name] => seasonal fruit
[type] => Fruit
[measurement] =>
[amount] => 3
)
)
[protein] => Array (
[16] => Array (
[id] => 16
[name] => soy yogurt
[type] => protein
[measurement] =>
[amount] => 2
)
[18] => Array (
[id] => 18
[name] => oilseed
[type] => protein
[measurement] => grip
[amount] => 3
)
)
[lipid] => Array (
[19] => Array (
[id] => 19
[name] => coconut powder
[type] => lipid
[measurement] => Tablespoon
[amount] => 2
)
[20] => Array (
[id] => 20
[name] => chocolate powder
[type] => lipid
[measurement] => Tablespoon
[amount] => 2
)
[38] => Array (
[id] => 38
[name] => chocolate square
[type] => lipid
[measurement] =>
[amount] => 1
)
)
)
You were not far off, but everything you are interested in ins inside the inner foreach, that way you dont get the Fruit and Protien etc involved
$courses = [];
foreach( $array as $sub){
foreach ($sub as $item) {
if ( array_key_exists($item['id'], $courses) ) {
// dup, so just add to the amount
$courses[$item['id']]['amount'] += $item['amount'];
} else {
//New entry
$courses[$item['id']] = $item;
}
}
}
// if its important to have indexes starting at 0 for the result
$courses = array_values($courses);

Php merge two elements of an array based on some common value and add other values

I have a below array:
[product] => Array
(
[0] => Array
(
[qty] => 1
[code] => 147818
[price] => 11
[name] => Product1
)
[1] => Array
(
[qty] => 2
[code] => 147818
[price] => 11
[name] => Product1
)
[2] => Array
(
[qty] => 1
[code] => 567432
[price] => 31
[name] => Product2
)
)
I want to add quantities if the code is same. That is, I want the resulting array to be:
[product] => Array
(
[0] => Array
(
[qty] => 3
[code] => 147818
[price] => 11
[name] => Product1
)
[1] => Array
(
[qty] => 1
[code] => 567432
[price] => 31
[name] => Product2
)
)
It should merge the elements only if the code is same. How can I achieve this?
Try this code, it merge and sum the qty by code
$products = [
[
'qty' => 1,
'code' => 147818,
'price' => 11,
'name' => 'Product1'
],
[
'qty' => 2,
'code' => 147818,
'price' => 11,
'name' => 'Product1'
],
[
'qty' => 1,
'code' => 567432,
'price' => 31,
'name' => 'Product2'
],
];
$output = [];
for ($i=0; $i<count($products); $i++) {
if ($output[$products[$i]['code']]['code'] == $products[$i]['code']) {
$output[$products[$i]['code']]['qty'] += $products[$i]['qty'];
}else{
$output[$products[$i]['code']] = $products[$i];
}
}
$output = array_values($output);
print_r($output);

How to iterate this PHP array using foreach

I use this code to get data from API in form of Array:
$GetCurrentStock = $MyApi->GetCurrentStock('Array');
print_r($GetCurrentStock);
I am getting data in the form of Array like this:
Array ( [Status] => Ok [ReturnVal] => Array ( [0] => Array ( [name] => Alcatel [model] => Hero OT-8020X [color] => Black [warehouse] => HU11 [bar_code] => A20200125 [in_stock] => <20 [exp_delivery] => 0 [exp_available] => <20 [delivery_date] => - [price] => 301.90 [properties] => Array ( [eu_warranty] => no [keypad] => Touch screen [manual] => Hun [simlock] => Sim Free [remarks] => Data cable, headset [language] => ger, eng, esp, fra, ita, hun, ned, por, rom, tur [country] => China ) [ean] => [image] => http://www.mobileshop.bz/phone-pictures/api/3531-alcatel-hero-ot-8020x.jpg [id] => 3531 [category] => mobile ) [1] => Array ( [name] => Alcatel [model] => Idol 2 Mini OT-6016X [color] => Gray [warehouse] => HU11 [bar_code] => A20200121 [in_stock] => <5 [exp_delivery] => 0 [exp_available] => <5 [delivery_date] => - [price] => 192.60 [properties] => Array ( [eu_warranty] => no [keypad] => Touch screen [manual] => Hun [simlock] => Sim Free [remarks] => Data cable, headset [language] => cat, ger, eng, esp, fra, ita, hun, ned, por, rom, tur [country] => China ) [ean] => [image] => http://www.mobileshop.bz/phone-pictures/api/3345-alcatel-idol-2-mini-ot-6016x.jpg [id] => 3345 [category] => mobile ) [2] => Array ( [name] => Alcatel [model] => Idol 2 Mini OT-6016X [color] => White [warehouse] => HU11 [bar_code] => A20200120 [in_stock] => <5 [exp_delivery] => 0 [exp_available] => <5 [delivery_date] => - [price] => 192.60 [properties] => Array ( [eu_warranty] => no [keypad] => Touch screen [manual] => Hun [simlock] => Sim Free [remarks] => Data cable, headset [language] => cat, ger, eng, esp, fra, ita, hun, ned, por, rom, tur [country] => China ) [ean] => [image] => http://www.mobileshop.bz/phone-pictures/api/3346-alcatel-idol-2-mini-ot-6016x.jpg [id] => 3346
I have to add each product from the data programmatically to my database.
A single product is added like this:
$productData = array(
'product_description' => array('1' => array('name' => 'Alcatel', 'meta_description' => '' ,'meta_keyword' =>'', 'description' => '', 'tag' =>'')),
'model' => 'Alcatel Hero OT-8020X Black',
'price' => '301.40',
'tax_class_id' => 0,
'quantity' => 1,
'minimum' => 1,
'subtract' => 1,
'stock_status_id' => 6,
'shipping' => 1 ,
'image' => 'http://www.mobileshop.bz/phone-pictures/api/3531-alcatel-hero-ot-8020x.jpg',
'manufacturer' => 'Alcatel',
'manufacturer_id' => 44,
'category' => 'ce',
'product_category' => array('0' => 61),
'product_store' => array('0' => 0),
'date_available' => '2015-03-31',
'length_class_id' => 1,
'weight_class_id' => 1,
'status' => 1,
'sort_order' => 1,
);
//load model
$this->load->model('catalog/product');
// Attempt to pass the assoc array to the add Product method
$this->model_catalog_product->addProduct($productData);
How do I add all those product in bulk programmatically using foreach?
You can create a foreach loop for all the records you have got.
$this->load->model('catalog/product');
foreach($GetCurrentStock['ReturnVal'] as $value){
$productData = array(
'model' => $value['model'],
'price' => $value['price'],
);
// add other values in above array
$this->model_catalog_product->addProduct($productData);
}

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);

Best way to group array with same value

I need your help to solve this :)
i've this array
Array (
[0] => Array ( [order_id] => 121 [item_id] => 4344 [item_name] => Product [item_price] => 123 [item_type] => product [paypal_address] => email#test.com [qty] => 4 [currency] => EUR )
[1] => Array ( [order_id] => 121 [item_id] => 3444 [item_name] => Product1 [item_price] => 444 [item_type] => product [paypal_address] => email#test.com [qty] => 2 [currency] => EUR )
[2] => Array ( [order_id] => 121 [item_id] => 1233 [item_name] => Product2 [item_price] => 120 [item_type] => product [paypal_address] => email2#test.com [qty] => 18 [currency] => EUR )
)
I would like to loop on it and group them by values into a new array.
For example:
Pick all items in array that have the same paypal_address sum price, sum qty and move it into new array.
This is what i want to achieve, any tip / suggestion ?
EDIT:
At the end i want an array like this or similar:
Array (
[0] => Array ( [order_id] => 121 [items_id] => array(4344, 3444) [items_name] => 'Product , Product1' [amt] => 567 [item_type] => product [paypal_address] => email#test.com [qty] => 8 [currency] => EUR )
[1] => Array ( [order_id] => 121 [items_id] => 1233 [items_name] => Product2 [amt] => 120 [item_type] => product [paypal_address] => email2#test.com [qty] => 18 [currency] => EUR )
)
EDIT2:
what i did so far. but it doesn't work well and is not good to read.
$groupedParams = array();
foreach($params as $key=>$param){
if(!array_key_exists($param['paypal_address'], $groupedParams) && $param['item_type'] == 'product'){
$groupedParams[$param['paypal_address']] = array(
'order_id' => $param['order_id'],
'item_id' => $param['item_id'],
'item_name' => $param['item_name'],
'qty' => $param['qty'],
'amt' => $param['item_price'],
'item_type' => $param['item_type']
);
}else if(array_key_exists($param['paypal_address'], $groupedParams) && $param['item_type'] == 'product'){
$newItemId = $groupedParams[$param['paypal_address']]['item_id'].','.$param['item_id'];
$newAmt = (int)$groupedParams[$param['paypal_address']]['amt']+(int)$param['item_price'];
$newQty = (int)$groupedParams[$param['paypal_address']]['qty']+(int)$param['qty'];
$newItemName = (string)$groupedParams[$param['paypal_address']]['item_name'].' - '.(int)$param['item_name'];
$groupedParams[$param['paypal_address']] = array(
'order_id' => $param['order_id'],
'item_id' => $newItemId,
'item_name' => $newItemName,
'qty' => $newQty,
'amt' => $newAmt,
'item_type' => $param['item_type']
);
}
}
Thanks
You want to reorganise it to a cleaner format from what I understand, simply put:
$array = array();
foreach($params as $ar) {
$array[$ar['paypal_address']][] = $ar;
}
Example: http://jdl-enterprises.co.uk/sof/25767688.php
Get Array and its values
make unique key on paypal_address
Use unique key to create temp array
Store all values with respective unique key in temp array
$arr = Array (
'0' => Array ( 'order_id' => 121 ,'item_id' => 4344 ,'item_name' => 'Product' ,'item_price' => 123 ,'item_type' => 'product' ,'paypal_address' => 'email#test.com' ,'qty' => 4 ,'currency' => 'EUR' ) ,
'1' => Array ( 'order_id' => 121 ,'item_id' => 3444 ,'item_name' => 'Product1' ,'item_price' => 444 ,'item_type' => 'product' ,'paypal_address' => 'email#test.com' ,'qty' => 2 ,'currency' => 'EUR' ) ,
'2' => Array ( 'order_id' => 121 ,'item_id' => 1233 ,'item_name' => 'Product2' ,'item_price' => 120 ,'item_type' => 'product' ,'paypal_address' => 'email2#test.com' ,'qty' => 18 ,'currency' => 'EUR' )
);
$tmpArr = Array();
$cnt = sizeof($arr);
for($i=0;$i<$cnt;$i++){
$paypal_address = $arr[$i]['paypal_address'];
if(!is_array($tmpArr[$paypal_address])){
$tmpArr[$paypal_address] = Array();
}
$tmpArr[$paypal_address]['paypal_address'] = $arr[$i]['paypal_address'];
$tmpArr[$paypal_address]['order_id'] = $arr[$i]['order_id'];
$tmpArr[$paypal_address]['item_name'][] = $arr[$i]['item_name'];
$tmpArr[$paypal_address]['item_type'][] = $arr[$i]['item_type'];
$tmpArr[$paypal_address]['currency'][] = $arr[$i]['currency'];
$tmpArr[$paypal_address]['qty'] = isset($tmpArr[$paypal_address]['qty']) ? $tmpArr[$paypal_address]['qty'] + $arr[$i]['qty'] : $arr[$i]['qty'];
$tmpArr[$paypal_address]['item_id'] = $arr[$i]['item_id'];
$tmpArr[$paypal_address]['item_id'][] = $item_id;
$tmpArr[$paypal_address]['item_price'] = isset($tmpArr[$paypal_address]['item_price']) ? $tmpArr[$paypal_address]['item_price'] + $arr[$i]['item_price'] : $arr[$i]['item_price'];
}
print_r($tmpArr);
Output of the array is as below:
Array([email#test.com] => Array ([paypal_address] => email#test.com[order_id] => 121[item_name] => Array ( [0] => Product [1] => Product1 )[item_type] => Array ( [0] => product [1] => product )[currency] => Array ( [0] => EUR [1] => EUR )[qty] => 6[item_id] => 3444[item_price] => 567 )[email2#test.com] => Array ([paypal_address] => email2#test.com[order_id] => 121[item_name] => Array ( [0] => Product2 )[item_type] => Array ( [0] => product )[currency] => Array ( [0] => EUR )[qty] => 18[item_id] => 1233[item_price] => 120 ))
Note: Make changes in code according to your requirement
$details =Array (
[0] => Array ( [order_id] => 121 [item_id] => 4344 [item_name] => Product [item_price] => 123 [item_type] => product [paypal_address] => email#test.com [qty] => 4 [currency] => EUR )
[1] => Array ( [order_id] => 121 [item_id] => 3444 [item_name] => Product1 [item_price] => 444 [item_type] => product [paypal_address] => email#test.com [qty] => 2 [currency] => EUR )
[2] => Array ( [order_id] => 121 [item_id] => 1233 [item_name] => Product2 [item_price] => 120 [item_type] => product [paypal_address] => email2#test.com [qty] => 18 [currency] => EUR )
)
$sorted = array();
foreach ($details as $key => $value) {
$add = $value['paypal_address'];
foreach ($details as $index => $detail) {
if ($add == $detail['paypal_address']) {
foreach ($detail as $cat => $val) {
if (!in_array($val, $sorted[$key][$cat])) {
$sorted[$key][$cat][] = $val;
}
}
unset($details[$index]);
}
}
}
// Output array
print_r($sorted);

Categories