I am trying to dynamically get a specific data array by using a function (parsing an excel file, so for instance, I can grab the fourth column of the file as follows):
foreach ($obj->Worksheet->Table->Row as $row)
{
$rows[] = (string)$row->Cell[4]->Data;
}
My problem is im trying to dynamically specify the "cell" to get and I dont know how to properly format it as I cant use $ within the [] apparently. So Im trying to do this and its not working:
$col = 4;
foreach ($obj->Worksheet->Table->Row as $row)
{
$rows[] = (string)$row->Cell[$col]->Data;
}
Your expression works, but if you have more complicated expressions use braces.
$rows[] = (string)$row->{Cell[$col]}->Data;
Related
I'm using akeneo-labs spreadsheet-parser library to extract data from xlsx file.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
var_dump($rowIndex, $values);
}
Actually, you can get value by column index in a loop, is it possible to get value by column name instead?
maybe using another package as suggested fixes your problem.
also you can use array_column https://www.php.net/manual/en/function.array-column.php
Maybe you can do that in a spreadsheet CSV file by using PHP default function fgetcsv(), you can go throw an overview from here: https://www.php.net/manual/en/function.fgetcsv
fgetcsv — Gets line from file pointer and parse for CSV fields
First of all, save as your Xls file in CSV type then you can take your value from that CSV file by column name.
You can try this.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
// all columns
$columns = [];
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
if ($rowIndex == 1) {
$columns = $values;
} else {
$datum = array_combine($columns, $values);
// get value by column name
var_dump($datum['name']);
}
}
i want to display data from database and also i have created function in model file which is showing data from database but all values are shown in the array format.
problem is that when i print echo $values['title']; in foreach loop it is showing only first letter from title array??
model code
function reviewcitypage()
{
$cacheKey = 'city_page';
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
$cachedCategoryData = GigaCache::read($cacheKey);
if($cachedCategoryData && !cr('DynamicPage.field'))
{
$recentactivity = $cachedCategoryData;
}else
{
$recentactivity= $this->find("list",array("conditions"=>array("status"=>1),'fields'=>array('title','body','rating'),'recursive'=>-1,'limit'=>10));
//dont't set cache if dynamic field
if(!cr('DynamicPage.field'))
{
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
GigaCache::write($cacheKey,$recentactivity);
}
}
return $recentactivity;
}
view file
$ReviewObj = cri('Review');
$recentactivity = $ReviewObj->reviewcitypage();
foreach ($recentactivity as $name => $value){
foreach($value as $values)
{
echo $values['title'];
}
}
**problem is solved now thanks for support **
i have changed the code in model file and it is woking now
$recentactivity= $this-
>find("all",array("conditions"=>array("status"=>1),'recursive'=>-1,
'limit'=>10));
Your find() query is preparing the data as a 'list'. in cake lists are always key => value pair arrays. so in your view when you use the second foreach loop you are saying foreach character in a string...do.....
in your example $value can only be a string. foreaching it can only make $values a single char.
Let me know if you still unsure what i mean. not the best at explaining what i mean
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
Because you are after 3 fields I suggest using either first or all in place of list as the first argument in the find() method.
I'm trying to dynamically generate html select options using PHP based on whatever its stored in mysql database.
the column that stores the data called sizez.
the data in that column is stored like so:
small,large,xlarge,xxlarge
so basically the data is separated by a comma.
now in my php page I simply pull the data and display it on my page using a while loop for each product that is stored in the mysql database.
the issue that I am having is that I need to generate a select option dropdown list based on the sizez column for each item.
for that I am using the explode() function and it will generate the select option successfully too.
however, the issue is that it will only get the strings from the first sizez column and ignores the rest of the items But it will display the string from the first column for other items too and it repeats them!
this is my code:
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
$all_list .="<select>
'.$sizesOption.'
</select>";
so I thought to put the foreach($array as $value) inside the $all_list .= but that approach is wrong.
could someone please advise on this issue?
any help would be appreciated.
EDIT:
The expected result should be like this:
item one item two item three
small large small
large xxlarge xxlarge
However, with my code I get the result like this:
item one item two item three
small small small
large large large
small small
large large
small
large
so basically, it will get the sizes column from the first item and it will repeat it inside select options for other items exactly like the example above.
Since you are generating separate <select> for each iteration, you have to reset $sizeOptions. I suggest using arrays instead of just concatenating strings:
$allList = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$sizesOption = array();
$sizez = preg_replace('/\.$/', '', $row["sizez"]);
$array = explode(',', $sizez);
foreach ($array as $value) {
$sizesOption[] = "<option>{$value}</option>";
}
$all_list[] = '<select>'.implode("\r\n", $sizesOption).'</select>';
}
echo implode("\r\n", $allList);
From what you have posted it looks like you're regenerating $all_list in every iteration of your while loop.
So if you echo $all_list outside of the while loop it will only have the last iteration available - all the other ones having been overwritten during the process of the while loop.
Maybe I am wrong. but as simple as:
$all_list ="<select>".$sizesOption."</select>";
Close the opening braces for while loop before the '$all_list .="' statement.You are iterating the statement inside while loop.
`
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
}
$all_list .="<select>
'.$sizesOption.'
</select>";
`
May be this will work
I figured it out. Thanks to Justinas's answer. I realized that I had to put my php variable inside the while loop.
so all I had to do was to put $sizesOption =array(); inside my while loop and everything works fine now.
P.S. i haven't made any other changes to my code above.
I have this current structure:
{"resultset":[
{"IM":[2],"SR":[2],"TA":[4],"PMT":[2],"IMT":[2]},
{"IM":[1],"SR":[0],"TA":[4],"PMT":[1],"IMT":[0]},
{"IM":[2],"SR":[5],"TA":[17],"PMT":[2],"IMT":[5]}
]
}
I need to generate a foreach loop (I think) searching an each key and transforming the structure to look like this instead:
{"resultset":[ {"IM":[2,1,2],"SR":[2,0,5],"TA":[4,4,17],"PMT":[2,1,2],"IMT":[2,0,5]} ]}
I know I have to use a foreach loop and search on the key and then push the data back into a new array with this structure. but im having difficulty getting my head around it. any help would be appreciated.
I might need to change my strategy here:
this is my current code that is generated the first array:
for($i=0; $i<sizeof($teams);$i++)
{
$openResultSet['resultset'][] = $DAL->runGenericSQL(TotalTicketsInQueue($teams[$i]),"open",$i);
}
this calls the following (in a nutshell)
while ($row = odbc_fetch_array($resultSet))
{
$OpenTicketResultArray["IM"][] = intval($row["IM"]);
$OpenTicketResultArray["SR"][] = intval($row["SR"]);
$OpenTicketResultArray["TA"][] = intval($row["TA"]);
$OpenTicketResultArray["PMT"][] = intval($row["IM"]);
$OpenTicketResultArray["IMT"][] = intval($row["SR"]);
}
return $OpenTicketResultArray;
I'm thinking at each iteration when the first array comes back store the results in a new key'd array and then continue to push the new results. but I'm new to this :(
I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.