Here is my foreach
<?php
foreach ($_productCollection as $_product){
echo "<PRE>";
print_r($_product->getData());
}
?>
foreach Array Output:-
Array
(
[entity_id] => 85
[name] => Round Bur
)
Array
(
[entity_id] => 86
[name] => testile Bur
)
Array
(
[entity_id] => 87
[name] => Shovel
)
Array
(
[entity_id] => 88
[name] => Round Bur
)
I want to remove the same name array under foreach for example
Actual Output
Array
(
[entity_id] => 85
[name] => Round Bur
)
Array
(
[entity_id] => 86
[name] => testile Bur
)
Array
(
[entity_id] => 87
[name] => Shovel
)
How to remove the last 1 arrays because of a name as same. please give me a solution
You can put all the results in an array, only adding them if the namedoesn't already exist:
$products = array();
foreach ($_productCollection as $_product){
$product = $_product->getData();
if (!in_array($product['name'], array_column($products, 'name'))) {
$products[] = $product;
}
}
echo "<PRE>";
print_r($products);
You can splice repeated row which contains the same value:
$res_ar = []; // resultant array
$ar_names = []; // array of unique names
foreach($ar as $ind => $row){
if (in_array($row['name'],$ar_names)){ // if name was before
array_splice($ar,$ind,1); // remove element by its index
} else {
$ar_names[] = $row['name']; // add new name to the unique array of names
$res_ar[] = $row; // saving row with new name value
}
}
Demo
Implementation for your case looks like next:
$res_ar = [];
$ar_names = [];
foreach ($_productCollection as $ind => $_product){
$row = (array)$_product->getData();
if (in_array($row['name'], $ar_names)){
array_splice($_productCollection,$ind,1);
} else {
$ar_names[] = $row['name'];
$res_ar[] = $_product;
}
}
One last version, just keep a track of the names added, but also add the original to the output rather than the array of data...
$output = [];
$existingNames = [];
foreach ($_productCollection as $product){
$productName = $product->getData()['name'];
if ( !isset($existingNames[$productName])) {
$existingNames[$productName] = true;
$output[] = $product;
}
}
Related
How to make this array from foreach in my code?
Below is my code
Array
(
[0] => Array
(
[day] => 2016-11-21
)
[1] => Array
(
[day] => 2016-11-22
)
[2] => Array
(
[day] => 2016-11-23
)
[3] => Array
(
[day] => 2016-11-24
)
[4] => Array
(
[day] => 2016-11-25
)
)
Below is my code but the result is different.
The result is from foreach and I want it to be an array, just like the array above.
foreach ($data['my_undertime'] as $undertime_row) {
$datetimein = new DateTime($undertime_row->timein);
$datetimein->format('h:m:s');
$datetimeout = new DateTime($undertime_row->timeout);
$datetimeout->format('h:m:s');
$items = array();
if ($datetimein->format('h:m:s') > $undertime_row->beg_time && $datetimeout->format('h:m:s') < $undertime_row->end_time) {
// echo $undertime_row->day;
$items[]['day'] = $undertime_row->day;
}
echo "<pre>";
print_r($items);
}
Please help.
Thanks.
The problem is in the line $items = array();.
As it is now, $item is recreated on each loop. After the foreach it ends up remembering only the last iteration of the loop.
If you want to keep all the data in $item then move this line of code before the foreach loop.
$items = array();
$i = 0;
foreach ($data['my_undertime'] as $undertime_row) {
$datetimein = new DateTime($undertime_row->timein);
$datetimein->format('h:m:s');
$datetimeout = new DateTime($undertime_row->timeout);
$datetimeout->format('h:m:s');
if ($datetimein->format('h:m:s') > $undertime_row->beg_time && $datetimeout->format('h:m:s') < $undertime_row->end_time) {
// echo $undertime_row->day;
$items[$i]['day'] = $undertime_row->day;
}
$i++;
}
echo "<pre>";
print_r($items);
try this
Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...
I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here
I've a $_POST that sends an array. And i've a prevoious array with contains a key that could contain or not one of the values from teh $_POST.
For Example:
$_post: Array ( [0] => 13 [1] => 10 [2] => 52)
Previous: Array ( [0] => Array ( [collection_id] => 13 [artwork_id] => 21 )
[1] => Array ( [collection_id] => 11 [artwork_id] => 21 ) )
So i need to check if the $_POST itms already exists on the previuos array ([collection_id] key) and extract the new ones (in this case [1] => 10 [2] => 52) to ve added to the database and also get those which has changed that need to be removed from the database (replaced) by the new values.
This my current code but not working well...
$new_nodes = array();
$i = 0;
foreach($old_nodes as $node){
foreach ($collections as $collection) {
$new = array('collection_id' => $collection, 'artwork_id' => $artwork['id']);
if(array_diff($node, $new)){
if($collection > 0){
array_push($new_nodes, $new);
}
}
else{
unset($old_nodes[$i]);
}
}
$i++;
}
foreach($new_nodes as $node){
for ($i = 0; $i <= count($new_nodes); $i++) {
if(isset($new_nodes[$i])){
if(!array_diff($node, $new_nodes[$i])){
unset($new_nodes[$i]);
}
}
}
}
NOTE: old_nodes is "Previous" and $collections is "$_POST"
Try something like this:
$old_nodes = array();
$new_nodes = array();
$del_nodes = array();
foreach ($collections as $collection) {
array_push($old_nodes, $collection['collection_id']);
}
$new_nodes = array_diff($collections, $old_nodes);
$del_nodes = array_diff($old_nodes, $collections);
I have the following issue, I have an array with the name $data
Within this array I have something like
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
In some elements the code value is the same, now what I want to do is merge all the elements with the same code value together, and adding the totals together. I tried doing this in a foreach loop, but does not seem to work.
I do something like this
$old_lc = null;
$old_lcv = 0;
$count = 0;
$dd = null;
foreach($data as $d){
if($d['code'] == $old_lc){
$d['total'] = $d['total'] + $old_lcv;
$count--;
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
}else{
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
$count++;
}
$old_lc = $d['code'];
$old_lcv = $d['total'];
}
$data = $dd;
But this does not seem to work. Also I need the $data array to keep the keys, and should remain in the same format
$result = array();
foreach($ary as $elem) {
$code = $elem['code'];
$total = $elem['total'];
if(!isset($result[$code]))
$result[$code] = 0;
$result[$code] += $total;
}
This code translates the above array into an array of code => total.
$out = array();
foreach ($data as $k => $v) {
$out[$v['code']] += $v['total'];
}
It is worth noting that on certain settings this will generate a warning about undefined indexes. If this bothers you, you can use this alternate version:
$out = array();
foreach ($data as $k => $v) {
if (array_key_exists($v['code'], $out)) {
$out[$v['code']] += $v['total'];
} else {
$out[$v['code']] = $v['code'];
}
}
This turns it back into something like the original, if that's what you want:
$output = array();
foreach ($out as $code => $total) {
$output[] = array('code' => $code, 'total' => $total);
}
Note: the original keys of $data aren't maintained but it wasn't stated that this was a requirement. If it is, it needs to be specified how to reconstruct multiple elements that have the same code.
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
$data_rec = array();
$data = array();
foreach($data_rec as $key=>$rec)
{
$data[$key]+= $rec[$key];
}
print_r($data);