How to make an array from foreach? - php

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

Related

Php parse multilevel - xml into array

I am trying to convert xml into php array but somehow i am doing a mistake, can anyone please help me ?
Here the xml formate :
<Department Id="3">
<Week Date="23/03/2020">
<Class DateTime="23/03/2020 18:00"/>
<Class DateTime="23/03/2020 18:45"/>
</Week>
<Week Date="30/03/2020">
<Class DateTime="30/03/2020 18:00"/>
<Class DateTime="30/03/2020 18:45"/>
</Week>
</Department>
Output Need like this :
Array
(
[0] => Array
(
[0] => Array
(
[DateTime] => 23/03/2020 18:00
)
[1] => Array
(
[DateTime] => 23/03/2020 18:45
)
)
[1] => Array
(
[0] => Array
(
[DateTime] => 30/03/2020 18:00
)
[1] => Array
(
[DateTime] => 30/03/2020 18:45
)
)
)
This is what i have tried
foreach ($xml->children() as $week) {
foreach ($week->children() as $class) {
$j = 0;
foreach ($class->attributes() as $a => $b){
$results[$i][$j][$a] = (string) $b;
}
$j++;
}
$i++;
}
I dont know whats wrong in my code :(
It's just a case of getting the right levels in the XML to match the loops, this builds a weeks data at a time and adds it into the overall results...
$results = [];
foreach ( $xml->Week as $week ) {
$weekData = [];
foreach ( $week->Class as $class ) {
$weekData[]['DateTime'] = (string)$class['DateTime'];
}
$results[] = $weekData;
}
To make this load all attributes...
$results = [];
foreach ( $xml->Week as $week ) {
$weekData = [];
foreach ( $week->Class as $class ) {
$classData = [];
foreach ( $class->attributes() as $name => $value ) {
$classData[$name] = (string)$value;
}
$weekData[] = $classData;
}
$results[] = $weekData;
}

Remove same name array

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

How to display values inside multi-dimensional array in php

I would like to get the values of id and name inside this array.
Array
(
[data] => Array
(
[0] => Array
(
[id] => 238345159549706
[members] => Array
(
[data] => Array
(
[0] => Array
(
[id] => 100001130889528
[name] => Sy Cheeze
)
[1] => Array
(
[id] => 100002616426665
[name] => Chun Jenny
)
.......
I've tried using this foreach.
foreach ($acquaintances as $acquaintance)
{
foreach ($acquaintance as $acquaint)
{
$acqID = $acquaint['id'];
$acqName = $acquaint['name'];
echo $acqName;
}
}
but nothing will be displayed. What would I do with my code? Any idea and suggestions please. Thank you!
$array = array
(
array("bla",22,18),
array("blaa",15,13),
array("blaaa",5,2),
array("blaaaa",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$array[$row][$col]."</li>";
}
echo "</ul>";
}
You can also access the indices directly in your foreach loop. Like this:
foreach($acquaintances['data'] as $acquaintance) {
foreach($acquaintance['members']['data'] as $acquaint) {
$acqID = $acquaint['id'];
$acqName = $acquaint['name'];
echo $acqName . '<br/>';
}
}

Associative index array to associative associative array

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...

Array Looping and Counting String Occurrences PHP

Anyone know what I'm doing wrong?
From the following array I want to count the the number of times "Friday" occurs.
Array (
[404979509517702] => Array (
[0] => 235
[1] => 04:10,Friday
)
[404045862944400] => Array (
[0] => 192
[1] => 23:52,Wednesday
)
[20403274909688162] => Array (
[0] => 186
[1] => 22:21,Tuesday
)
[202735273075459] => Array (
[0] => 336
[1] => 04:29,Tuesday
)
[652948031457462] => Array (
[0] => 410
[1] => 06:22,Monday
)
[2606749954978] => Array (
[0] => 312
[1] => 05:01,Saturday
)
[755318061725] => Array (
[0] => 384
[1] => 04:51,Friday
)
)
This is what I'm doing:
$friday = array();
foreach ($the_array as $friday){
$the_array = explode(',', $friday[1]);
$the_array[$the_array [1]] += ($friday[1]);
}
print_r($friday);
This way, I get the wrong number of "Friday" occurrences.
Any idea what I'm doing wrong or if there is a more elegant solution to that?
I would try something like the following if all you want to do is count occurrences:
$friday_count = 0;
foreach($the_array as $record) {
// Search for "Friday"
if(stristr($record[1],'Friday') !== false) {
$friday_count++; // increment count
}
}
$fridayCount = 0;
foreach ($the_array as $friday){
$friArr = explode(',', $friday[1]);
if($friArr[1] == "Friday") {
$fridayCount++;
}
}
echo ($fridayCount);
The code should be:
$fridayCount = 0;
foreach ($the_array as $friday){
if(strrpos($friday[1], 'Friday') !== false) {
$fridayCount++;
}
}
echo $fridayCount;
I think you might be complicating this unnecessarily. You should be able to test for 'Friday' and increment a counter ($friday, here) as follows:
$friday = 0;
foreach ($the_array as $element){
if (array_pop(explode(',', $element[1])) == 'Friday') {
$friday++;
}
}
echo $friday;
$cnt = 0;
foreach ($the_array as $friday){
if (explode(',', $friday[1]) == 'Friday') {
$cnt++;
}
}
echo $cnt;

Categories