im using yii2 framework
I have array coming from controller to the view.
public function actionProducts()
{
$product = Yii::$app->httpclient->get('http://localhost/MWSProducts/src/MarketplaceWebServiceProducts/Samples/GetMatchingProductSample.php');
$array1 = str_replace("ns2:","",$product);
$array=json_decode(json_encode(simplexml_load_string($array1)),true);
return $this->render('products',['array'=>$array]);
}
In the above code im converting xml to an array.
The $array has the array, and im passing it to view called products. Now i want to display that array in the view in Gridview, Since im new to yii2 im unable to do this, it says i have to use some dataprovider, but im not getting how to do this.
Can anyone please help me in this how do i display the array in gridview. Thank you
Thanks for the answer..
Actually its a amazon product array im fetching it from the Product API, we cant define any predefine attributes like id and all, since its different for each product. this is how the array looks like.
Array
(
[GetMatchingProductResult] => Array
(
[0] => Array
(
[#attributes] => Array
(
[ASIN] => 0886467918
[status] => Success
)
[Product] => Array
(
[Identifiers] => Array
(
[MarketplaceASIN] => Array
(
[MarketplaceId] => A21TJRUUN4KGV
[ASIN] => 0886467918
)
)
[AttributeSets] => Array
(
[ItemAttributes] => Array
(
[Author] => Kipling, Rudyard
[Binding] => Hardcover
[Edition] => Har/Cas
[Format] => Import
[Label] => Imprint unknown
[Languages] => Array
(
[Language] => Array
(
[0] => Array
(
[Name] => english
[Type] => Published
)
[1] => Array
(
[Name] => english
[Type] => Original Language
)
[2] => Array
(
[Name] => english
[Type] => Unknown
)
)
)
[Manufacturer] => Imprint unknown
[PackageDimensions] => Array
(
[Weight] => 1.74
)
[ProductGroup] => Book
[ProductTypeName] => ABIS_BOOK
[PublicationDate] => 1988-05-02
[Publisher] => Imprint unknown
[SmallImage] => Array
(
[URL] => http://ecx.images-amazon.com/images/I/412CsE6Mb8L._SL75_.jpg
[Height] => 75
[Width] => 50
)
[Studio] => Imprint unknown
[Title] => Jungle Book ("Read Along")
)
)
[Relationships] => Array
(
)
[SalesRankings] => Array
(
[SalesRank] => Array
(
[0] => Array
(
[ProductCategoryId] => book_display_on_website
[Rank] => 709468
)
[1] => Array
(
[ProductCategoryId] => 1318084031
[Rank] => 14260
)
[2] => Array
(
[ProductCategoryId] => 1318083031
[Rank] => 47016
)
)
)
)
)
If the array contain the data like a dataProvider . you can use arrayDataProvider http://www.yiiframework.com/doc-2.0/yii-data-arraydataprovider.html eg (from yii2 guide):
$data = [
['id' => 1, 'name' => 'name 1', ...],
['id' => 2, 'name' => 'name 2', ...],
...
['id' => 100, 'name' => 'name 100', ...],
];
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => ['id', 'name'],
],
]);
a brief guide to dataprovider http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html
in your case
public function actionProducts()
{
$product = Yii::$app->httpclient->get('http://localhost/MWSProducts/src/MarketplaceWebServiceProducts/Samples/GetMatchingProductSample.php');
$array1 = str_replace("ns2:","",$product);
$array=json_decode(json_encode(simplexml_load_string($array1)),true);
$provider = new ArrayDataProvider([
'allModels' => $array,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('products',['array'=>$array]);
}
Refer to sample above where the array $data contain id, name and suppose your arrayDataProvider is in the var $array and have id,name too in gridview you should have
<?= GridView::widget([
'dataProvider' => $array,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
.....
['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['style' => 'width:84px; font-size:18px;']],
],
]); ?>
Related
I have an array of objects for example:
Array
(
[0] => Array
(
[Id] => 1
[Name] => Toy Car
[Category] => Toys
[Price] => 2.99
[OnSale] => false
)
...
)
But I'd like them to be grouped by Category, then by OnSale.
So far I have been able to group by category using:
$result = array();
foreach ($data as $element) {
$result[$element['Category']][] = $element;
}
But I am unsure how to nest another foreach or recursively group them once they have been grouped by Category. Any help is appreciated!
Do you mean:
$result = array();
foreach ($data as $element) {
$result[$element['Category']][$element['OnSale']][] = $element;
}
EDIT: Sorry, bit of a problem with all the [ and ]...
You're close! You just need to add the second key you want to group by.
$byCategoryAndSale = [];
foreach ($inventory as $item) {
$byCategoryAndSale[$item['Category']][$item['OnSale']][] = $item;
}
Note Using a boolean value as an array key will equate to 1's and 0's which can get pretty confusing.
Here's a full example:
<?php
$inventory = [
[
'Id' => 1,
'Name' => 'Toy Car',
'Category' => 'Toys',
'Price' => 2.99,
'OnSale' => false
],
[
'Id' => 2,
'Name' => 'Another Toy',
'Category' => 'Toys',
'Price' => 1.99,
'OnSale' => false
],
[
'Id' => 3,
'Name' => 'Hamburger',
'Category' => 'Not Toys',
'Price' => 5.99,
'OnSale' => false
],
[
'Id' => 4,
'Name' => 'Last Toy',
'Category' => 'Toys',
'Price' => 50.99,
'OnSale' => true
]
];
$byCategoryAndSale = [];
foreach ($inventory as $item) {
$byCategoryAndSale[$item['Category']][$item['OnSale']][] = $item;
}
print_r($byCategoryAndSale);
?>
Which yields:
PS C:\> php test.php
(
[Toys] => Array
(
[0] => Array
(
[0] => Array
(
[Id] => 1
[Name] => Toy Car
[Category] => Toys
[Price] => 2.99
[OnSale] =>
)
[1] => Array
(
[Id] => 2
[Name] => Another Toy
[Category] => Toys
[Price] => 1.99
[OnSale] =>
)
)
[1] => Array
(
[0] => Array
(
[Id] => 4
[Name] => Last Toy
[Category] => Toys
[Price] => 50.99
[OnSale] => 1
)
)
)
[Not Toys] => Array
(
[0] => Array
(
[0] => Array
(
[Id] => 3
[Name] => Hamburger
[Category] => Not Toys
[Price] => 5.99
[OnSale] =>
)
)
)
)
I have tried using this example here Return index of highest value in an array
But that does not go into a multi dimensional Array
I have tried ARRAY_COLUMN(), array_values(), array_shift, Max and Min but they are not getting the info i need
I want to be able to loop thru and get to:
[pricing]
then Check pricing to see which is the highest and lowest in the nested array
so like below which total was the Highest and lowest trades on these dates
[2017-09-22]
[2017-09-23]
obviously [2017-09-23] is a simple one, i just dint want to add much more code for ppl helping to go thru.
The Array i create looks like this:
Array
(
[2017-09-23] => Array
(
[0] => Array
(
[timestamp] => 1506169387000
[pricing] => 9.5470
[qty] => 25
[total] => 238.675
[date] => 2017-09-23
)
)
[2017-09-22] => Array
(
[0] => Array
(
[timestamp] => 1506093083000
[pricing] => 9.6300
[qty] => 25
[total] => 240.75
[date] => 2017-09-22
)
[1] => Array
(
[timestamp] => 1506077220000
[pricing] => 8.7190
[qty] => 13
[total] => 113.347
[date] => 2017-09-22
)
[2] => Array
(
[timestamp] => 1506077109000
[pricing] => 8.6800
[qty] => 83
[total] => 720.44
[date] => 2017-09-22
)
[3] => Array
(
[timestamp] => 1506065258000
[pricing] => 8.7100
[qty] => 25
[total] => 217.75
[date] => 2017-09-22
)
)
in the example above i would like it to Create a new array with only the following
date -> last timestamp -> Highest pricing -> Lowest lowest -> Total of all Totals -> first Timestamp
EDIT: the last and first Timestamp are basically the first and last index so in this case:
[timestamp] => 1506093083000 and [timestamp] => 1506065258000
or Index [0] and index [3]
The array from your question:
$array = array (
'2017-09-23' =>
array (
0 =>
array (
'timestamp' => '1506169387000',
'pricing' => '9.5470',
'qty' => '25',
'total' => '238.675',
'date' => '2017-09-23',
),
),
'2017-09-22' =>
array (
0 =>
array (
'timestamp' => '1506093083000',
'pricing' => '9.6300',
'qty' => '25',
'total' => '240.75',
'date' => '2017-09-22',
),
1 =>
array (
'timestamp' => '1506077220000',
'pricing' => '8.7190',
'qty' => '13',
'total' => '113.347',
'date' => '2017-09-22',
),
2 =>
array (
'timestamp' => '1506077109000',
'pricing' => '8.6800',
'qty' => '83',
'total' => '720.44',
'date' => '2017-09-22',
),
3 =>
array (
'timestamp' => '1506065258000',
'pricing' => '8.7100',
'qty' => '25',
'total' => '217.75',
'date' => '2017-09-22',
),
),
);
To get the values maybe you can use array_map and with this the function array_column is the key of all, try with this:
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => reset($timestamps),
'last_timestamp' => end($timestamps),
];
}, $array);
$values is an array with the filter values that you need:
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => 1506169387000
[last_timestamp] => 1506169387000
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => 1506093083000
[last_timestamp] => 1506065258000
)
)
EDIT
Get the pricing of the [first_timestamp] and [last_timestamp]
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => [
'value' => reset($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
],
'last_timestamp' => [
'value' => end($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
]
];
}, $array);
I added an array to both timestamps with the value of these and the pricing.
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
[last_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => Array
(
[value] => 1506093083000
[pricing] => 9.6300
)
[last_timestamp] => Array
(
[value] => 1506065258000
[pricing] => 8.7100
)
)
)
<?php
[USED] => Array
(
[USER] => Array
(
[#attributes] => Array
(
[NAME] => locuz
[HOST] => srpth1cn03.local
[IP] => 10.106.2.48
[USED_LICENSES] => 1
[LOGIN_TIME] => 2014-12-10 07:34
[CHECKOUT_TIME] => 2014-12-10 07:34
)
)
)
I want to change above array to below:
[USED] => Array
(
[USER] => Array
(
[0] => Array
(
[#attributes] => Array
(
[NAME] => rdtank
[HOST] => it30992
[IP] => 10.106.21.134
[DENIED_LICENSES] => 1
[LOGIN_TIME] => 2014-12-09 15:55
[DENIAL_TIME] => 2014-12-09 15:55
)
)
)
)
Put a [] before you save attributes as below.
foreach($all_attributes as $attributes){
$sample_array['USED']['USER'][] = $attributes;
}
the code you wrote seems the result of 2 array dump.
so if you need to setup 2 variable in php that contains data you should use this code
<?php
$used = array(
'users' => array(
array(
'name' => 'locuz',
'host' => 'srpth1cn03.local',
'ip' => '10.106.2.48',
'used_licenses' => 1,
'login_time' => '2014-12-10 07:34',
'checkout_time' => '2014-12-10 07:34'
)
)
);
$denied = array(
'users' => array(
array(
'name' => 'rdtank',
'host' => 'it30992',
'ip' => '10.106.21.134',
'denied_licenses' => 1,
'login_time' => '2014-12-09 15:55',
'denial_time' => '2014-12-09 15:55'
)
)
);
hope this helps.
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
i've a similar array:
Array
(
[0] => Array
(
[id] => 1
[name] => Mario
[type] => Doctor
[operations] => brain
[balance] => 3.00
)
[1] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hearth
[balance] => 6.00
)
[2] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hands
[balance] => 4.00
)
[3] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => foots
[balance] => 1.00
)
)
I must to merge it for id, so obtain only 2 elements for array (0 and 1) and Luca (id 3) must be unified for operations, in a new array, similar to this, so in future print more clearly operations unified and not divided.
[...]
)
[1] => Array
(
[id] => 3
[name] => luca
[type] => doctore
[operations] => Array (6.00 hearts,
4.00 hands,
1.00 foots)
)
I can not figure how solve my trouble... Someone could help me please? Thank you very much to all!
<?php
$input = array(
array('id' => 1, 'name' => 'Mario', 'type' => 'Doctor', 'operations' => 'brain', 'balance' => 3.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hearth', 'balance' => 6.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hands', 'balance' => 4.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'foots', 'balance' => 1.00),
);
$output = array();
foreach ($input as $person)
{
// Add the person to the output, if needed.
if (array_key_exists($person['id'], $output) === false)
{
$output[$person['id']] =
array(
'id' => $person['id'],
'name' => $person['name'],
'type' => $person['type'],
'operations' => array(),
);
}
// Add the operation to the array of operations.
$output[$person['id']]['operations'][] =
array(
'type' => $person['operations'],
'balance' => $person['balance'],
));
}
foreach ($output as $person)
{
if (count($person['operations']) === 1)
{
// If the array contains only 1 item, pull it out of the array.
$output[$person['id']]['operations'] = $person['operations'][0];
}
}
print_r($output);