I'd like to load my array with objects from .csv
When I do it with writing JSON like a forced string, its okay and my code works fine.
When I try to make objects and load them into an array, new object overwrites all objects in the array and I got an array full of the same values. Any suggestions for my mistakes?
In the end, variable content gives valid JSON (without '[]' brackets), but array contentArr gives array full of same objects...
HereĀ“s the code:
$content = '';
$contentArr = array();
$Obj = new stdClass();
$count = 0;
while ($csv = fgetcsv($file,1000,",")) {
$content .= "{\"number\":\"".$csv[0]=Filter($csv[0])."\",\"message\":\"".$csv[1]."\"},";
$count++;
$Obj -> number = $csv[0]=Filter($csv[0]);
$Obj -> message = $csv[1];
$contentArr[] = $Obj;
}
$content = substr($content, 0, -1);
I hope this code can help you
$openFile = fopen($file, "r");
while(!feof($openFile)){
$csv = fgetcsv($file);
//your code here
}
fclose($openFile);
SOLVED MYSELF.
My mistake was that I was changing link only to one object I made before the while cycle. When I move object creating INTO the while cycle, I am creating new object for every new data I am loading into array.
Code:
$content = '';
$contentArr = array();
//$Obj = new stdClass(); ----> this was my mistake
$count = 0;
while ($csv = fgetcsv($file,1000,",")) {
$content .= "{\"number\":\"".$csv[0]=Filter($csv[0])."\",\"message\":\"".$csv[1]."\"},";
$count++;
$Obj = new stdClass();// ----> that's how it should be
$Obj -> number = $csv[0]=Filter($csv[0]);
$Obj -> message = $csv[1];
$contentArr[] = $Obj;
}
$content = substr($content, 0, -1);
Related
This is my first post on here. I am pretty new to coding and Powershell so I might be missing something obvious here. I made a QR code label maker for my work using Powershell and Smartsheet. Without getting into too much detail on that it pulls data from a line in a "Product Tracker" we made in Smartsheet and creates a label with a QR code from that data. In one of the columns on that line it mimics the data produced when you scan the QR code. It mimics it like this....
$SkuCell.Value = "BEGIN:VCARD
VERSION:3.0
KIND:individual
N:$($ptCO.Desc);$($ptCO.Po)
FN:$($ptCO.Po) $($ptCO.Desc)
ORG:All New Glass
EMAIL;TYPE=INTERNET:$($ptCO.Assign)
END:VCARD"
... and the output looks like this.....
BEGIN:VCARD
VERSION:3.0
KIND:individual
N:Test stuff here;12354
FN:12354 Test stuff here
ORG:All New Glass
EMAIL;TYPE=INTERNET:ericg#allnewglass.com
END:VCARD
Then on a different Smartsheet our drivers will scan the QR code on the label signifying that its leaving our hub. The scanned data in that cell looks like this.....
BEGIN:VCARD
VERSION:3.0
KIND:individual
N:Test stuff here;12354
FN:12354 Test stuff here
ORG:All New Glass
EMAIL;TYPE=INTERNET:ericg#allnewglass.com
END:VCARD
I then have a different script checking for matches between the two sheets so In the product tracker we know when something leaves the hub. The problem is that even though the scanned data and the mimicked data look absolutely identical and they both say they are strings, they never match. They are not equal to each other and I have tried EVERYTHING ([string], out-string, convert-string, compare-object, trim, etc) I can think of to get them to match and the only thing that works is if I pipeline Out-Host on the objects. However, these objects are contained in a foreach loop that checks through all the rows in both sheets which means that the script runs way to slow having to display all that data. It seems likely that there are some hidden characters in the scanned data causing them to not match. Can anyone think of a solution to make these two strings identical? Is there a way of removing all hidden characters? Or does anyone have a better idea? A different way to compare them maybe?
Here's the code that tries to compare....
# by GrEcHkO
#cd "C:\Users\Jacly\Desktop\ANG_System_Files"
cd "P:\ANG_System_Files"
function Load-Dll
{
param(
[string]$assembly
)
Write-Host "Loading $assembly"
$driver = $assembly
$fileStream = ([System.IO.FileInfo] (Get-Item $driver)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null;
$fileStream.Close();
$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);
}
function Get-ComparisonObjects
{
param([Smartsheet.Api.Models.Sheet]$sheet)
Write-Host "Getting Sheet $($sheet.Name) Comparison Objects"
$data = $sheet.Rows | foreach {
$checkVal = $false
$trackedCheckVal = $false
$finishedCheckVal = $false
if($_.Cells[3].Value -eq $true)
{
$checkVal = $true
}
if($_.Cells[16].Value -eq $true)
{
$trackedCheckVal = $true
}
if($_.Cells[12].Value -eq $true)
{
$finishedCheckVal = $true
}
[pscustomobject]#{
Attachments = $_.Attachments;
RowId = $_.Id;
RowNumber = $_.RowNumber;
Parent = $_.ParentId;
PoCol = $_.Cells[0].ColumnId;
Po = $_.Cells[0].Value;
JobsCol = $_.Cells[1].ColumnId;
Jobs = $_.Cells[1].Value;
DescCol = $_.Cells[2].ColumnId;
Desc = $_.Cells[2].Value;
CheckCol = $_.Cells[3].ColumnId;
Check = $checkVal;
SupplierCol = $_.Cells[4].ColumnId;
Supplier = $_.Cells[4].Value;
AssignCol = $_.Cells[5].ColumnId;
Assign = $_.Cells[5].Value;
DestinationCol = $_.Cells[11].ColumnId;
Destination = $_.Cells[11].Value;
FinishedCol = $_.Cells[12].ColumnId;
Finished = $finishedCheckVal;
DueCol = $_.Cells[14].ColumnId;
Due = $_.Cells[14].Value;
DeliveryCol = $_.Cells[15].ColumnId;
Delivery = $_.Cells[15].Value;
TrackedCol = $_.Cells[16].ColumnId;
Tracked = $trackedCheckVal;
SKUCol = $_.Cells[18].ColumnId;
SKU = $_.Cells[18].Value;
}
}| where {![string]::IsNullOrWhiteSpace($_.Po)}
Write-Host "$($data.Count) Returned"
return $data
}
function Get-DriverComparisonObjects
{
param([Smartsheet.Api.Models.Sheet]$sheet)
Write-Host "Getting Sheet $($sheet.Name) Comparison Objects"
$data = $sheet.Rows | foreach {
$checkVal = $false
$trackedCheckVal = $false
$finishedCheckVal = $false
$archiveCheckVal = $false
if($_.Cells[2].Value -eq $true)
{
$checkVal = $true
}
if($_.Cells[8].Value -eq $true)
{
$trackedCheckVal = $true
}
if($_.Cells[3].Value -eq $true)
{
$finishedCheckVal = $true
}
if($_.Cells[11].Value -eq $true)
{
$archiveCheckVal = $true
}
[pscustomobject]#{
Attachments = $_.Attachments;
RowId = $_.Id;
RowNumber = $_.RowNumber;
Parent = $_.ParentId;
DayCol = $_.Cells[0].ColumnId;
Day = $_.Cells[0].Value;
DueCol = $_.Cells[1].ColumnId;
Due = $_.Cells[1].Value;
CompletedCol = $_.Cells[2].ColumnId; #########hidden
Completed = $checkVal;
CheckCol = $_.Cells[3].ColumnId;
Check = $finishedCheckVal;
SupplierCol = $_.Cells[4].ColumnId;#########hidden
Supplier = $_.Cells[4].Value;
AssignCol = $_.Cells[5].ColumnId;#########hidden
Assign = $_.Cells[5].Value;
JobNameCol = $_.Cells[6].ColumnId;
JobName = $_.Cells[6].Value;
MainCol = $_.Cells[7].ColumnId;
Main = $_.Cells[7].Value;
TrackedCol = $_.Cells[8].ColumnId;
Tracked = $trackedCheckVal;
PoNumCol = $_.Cells[9].ColumnId;
PoNum = $_.Cells[9].Value;
ModifiedCol = $_.Cells[10].ColumnId;
Modified = $_.Cells[10].Value;
ArchiveCol = $_.Cells[11].ColumnId;
Archive = $archiveCheckVal;
}
} | where {![string]::IsNullOrWhiteSpace($_.PoNum)}
Write-Host "$($data.Count) Returned"
return $data
}
function Get-AttachmentFromSmartsheet
{
param (
[long]$attachmentId,
[long]$sheetId
)
Write-Host "Getting Attachement $attachmentId of Sheet $sheetId"
try
{
$attachment = $client.SheetResources.AttachmentResources.GetAttachment($sheetId,$attachmentId)
}
catch
{
Write-Error $_.Exception.Message
Write-Host ""
}
$downloads = New-Item -ItemType Directory ".\downloads" -Force
$filepath = "$($downloads.Fullname)\$($attachment.Name)"
Write-Host "Downloading $filepath"
Invoke-WebRequest -Uri $attachment.Url -OutFile $filepath
Get-Item $filepath
}
function Save-AttachmentToSheetRow
{
param(
[long]$sheetId,
[long]$rowId,
[System.IO.FileInfo]$file,
[string]$mimeType
)
Write-Host "Saving $($file.Fullname) to Sheet $sheetId"
$result = $client.SheetResources.RowResources.AttachmentResources.AttachFile($sheetId, $rowId, $file.FullName, $mimeType)
return $result
}
function Merge-DriverChecklistWithProductTracker
{
param(
[pscustomobject[]]$orbitalRecords,
[long]$orbitalId
)
foreach ($orbitalRecord in $orbitalRecords)
{
$descFound = $false
$skuFound = $false
if ($orbitalRecord.Archive -eq $false) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
foreach ($ptCO in $ptCOs) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
$orbitalQR = "$($orbitalRecord.PoNum)" #THIS IS WHERE I NEED HELP
$ptQR = "$($ptCO.SKU)" #THIS IS WHERE I NEED HELP
$noParent = $false #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
if ($orbitalQR -eq $ptQR) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
$descFound = $true #THIS IS WHERE I NEED HELP
break #THIS IS WHERE I NEED HELP
} #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
if ($orbitalQR -eq $ptQR) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
$skuFound = $true #THIS IS WHERE I NEED HELP
break #THIS IS WHERE I NEED HELP
} #THIS IS WHERE I NEED HELP
} #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
if ($skuFound) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
if (![string]::IsNullOrWhiteSpace($orbitalRecord.PoNum) -and ![string]::IsNullOrWhiteSpace($ptCO.SKU)) #THIS IS WHERE I NEED HELP
{ #THIS IS WHERE I NEED HELP
Write-Host "SKU found. Updating data on PT." #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
$destinationCell = [Smartsheet.Api.Models.Cell]::new() #THIS IS WHERE I NEED HELP
$destinationCell.ColumnId = $ptDestinationCol.Id #THIS IS WHERE I NEED HELP
$destinationCell.Value = "ITEM SCANNED TO ANG TRUCK" #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
$shippedCell = [Smartsheet.Api.Models.Cell]::new() #THIS IS WHERE I NEED HELP
$shippedCell.ColumnId = $ptShippedCol.Id #THIS IS WHERE I NEED HELP
$shippedCell.Value = if ($orbitalRecord.Modified -ne $null){$orbitalRecord.Modified} else {[string]::Empty} #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
$row = [Smartsheet.Api.Models.Row]::new() #THIS IS WHERE I NEED HELP
$row.Id = $ptCO.RowId #THIS IS WHERE I NEED HELP
$row.Cells = [Smartsheet.Api.Models.Cell[]]#($destinationCell, $shippedCell) #THIS IS WHERE I NEED HELP
#THIS IS WHERE I NEED HELP
$updateRow = $client.SheetResources.RowResources.UpdateRows($ptId, [Smartsheet.Api.Models.Row[]]#($row)) #THIS IS WHERE I NEED HELP
} #THIS IS WHERE I NEED HELP
} #THIS IS WHERE I NEED HELP
elseif ($orbitalRecord.PoNum -eq $ptCO.Po)
{
if ($descFound)
{
if ([string]::IsNullOrWhiteSpace($ptCO.Parent))
{
$noParent = $true
}
if ($noParent)
{
Write-Host "Updating Product Tracker with Driver Checklist $($orbitalRecord.PoNum) $($orbitalRecord.Main)"
$jobsCell = [Smartsheet.Api.Models.Cell]::new()
$jobsCell.ColumnId = $ptJobsCol.Id
$JobsCell.Value = if ($orbitalRecord.JobName -ne $null){$orbitalRecord.JobName} else {[string]::Empty}
$descCell = [Smartsheet.Api.Models.Cell]::new()
$descCell.ColumnId = $ptDescCol.Id
$descCell.Value = if ($orbitalRecord.Main -ne $null){$orbitalRecord.Main} else {[string]::Empty}
$checkCell = [Smartsheet.Api.Models.Cell]::new()
$checkCell.ColumnId = $ptCheckCol.Id
$checkCell.Value = $orbitalRecord.Completed
$assignCell = [Smartsheet.Api.Models.Cell]::new()
$assignCell.COlumnId = $ptAssignCol.Id
$assignCell.Value = if ($orbitalRecord.Assign -ne $null){$orbitalRecord.Assign} else {"ianz#allnewglass.com"}
$supCell = [Smartsheet.Api.Models.Cell]::new()
$supCell.COlumnId = $ptSupplierCol.Id
$supCell.Value = if (($orbitalRecord.Completed -eq $false) -and ($orbitalRecord.Supplier -eq "In Shop FAB")){$suppliers["$fabId"]} else {$suppliers["$DriveId"]}
$finishedCell = [Smartsheet.Api.Models.Cell]::new()
$finishedCell.ColumnId = $ptFinishedCol.Id
$finishedCell.Value = $orbitalRecord.Check
$row = [Smartsheet.Api.Models.Row]::new()
$row.Id = $ptCO.RowId
$row.Cells = [Smartsheet.Api.Models.Cell[]]#($JobsCell, $checkCell, $supCell, $assignCell, $finishedCell)
try
{
$updateRow = $client.SheetResources.RowResources.UpdateRows($ptId, [Smartsheet.Api.Models.Row[]]#($row))
$reference = if ($orbitalRecord.Attachments.Name -ne $null){$orbitalRecord.Attachments.Name} else {[string]::Empty}
$difference = if ($ptCO.Attachments.Name -ne $null){$ptCO.Attachments.Name} else {[string]::Empty}
$compareResults = Compare-Object -ReferenceObject $reference -DifferenceObject $difference -IncludeEqual -SyncWindow ([int]::MaxValue)
$missing = $compareResults | where SideIndicator -eq '<='
$missingAttachments = $missing.InputObject
$attachmentsToGet = $orbitalRecord.Attachments | where Name -in $missingAttachments
foreach($attachment in $attachmentsToGet)
{
Write-Host "Adding missing attachment $($attachment.name)"
$file = Get-AttachmentFromSmartsheet -attachmentId $attachment.Id -sheetId $orbitalId
$result = Save-AttachmentToSheetRow -sheetId $ptId -rowId $newRow.Id -file $file.FullName -mimeType $attachment.MimeType
}
}
catch
{
Write-Error $_.Exception.Message
Write-Host ""
}
if ($orbitalRecord.Check -eq $true)
{
$dateCell = [Smartsheet.Api.Models.Cell]::new()
$dateCell.ColumnId = $ptShippedCol.Id
$dateCell.Value = $orbitalRecord.Modified
$row = [Smartsheet.Api.Models.Row]::new()
$row.Id = $ptCO.RowId
$row.Cells = [Smartsheet.Api.Models.Cell[]]#($dateCell)
try
{
$updateRow = $client.SheetResources.RowResources.UpdateRows($ptId, [Smartsheet.Api.Models.Row[]]#($row))
}
catch
{
Write-Error $_.Exception.Message
Write-Host ""
}
}
if (![string]::IsNullOrWhiteSpace($orbitalRecord.Due))
{
$dateCell = [Smartsheet.Api.Models.Cell]::new()
$dateCell.ColumnId = $ptAnticipatedCol.Id
$dateCell.Value = $orbitalRecord.Due
$row = [Smartsheet.Api.Models.Row]::new()
$row.Id = $ptCO.RowId
$row.Cells = [Smartsheet.Api.Models.Cell[]]#($dateCell)
try
{
$updateRow = $client.SheetResources.RowResources.UpdateRows($ptId, [Smartsheet.Api.Models.Row[]]#($row))
}
catch
{
Write-Error $_.Exception.Message
Write-Host ""
}
}
}
}
}
else
{
if (!($descFound -or $skuFound))
{
if (![string]::IsNullOrWhiteSpace($orbitalRecord.PoNum))
{
if ($orbitalRecord.Tracked -eq "$true")
{
Write-Host "Adding to Product Tracker from Driver Checklist $($orbitalRecord.Po) $($orbitalRecord.Main)"
$poCell = [Smartsheet.Api.Models.Cell]::new()
$poCell.ColumnId = $ptPoCol.Id
$poCell.Value = if ($orbitalRecord.PoNum -ne $null){$orbitalRecord.PoNum} else {[string]::Empty}
$jobsCell = [Smartsheet.Api.Models.Cell]::new()
$jobsCell.ColumnId = $ptJobsCol.Id
$JobsCell.Value = if ($orbitalRecord.JobName -ne $null){$orbitalRecord.JobName} else {[string]::Empty}
$descCell = [Smartsheet.Api.Models.Cell]::new()
$descCell.ColumnId = $ptDescCol.Id
$descCell.Value = if ($orbitalRecord.Main -ne $null){$orbitalRecord.Main} else {[string]::Empty}
$checkCell = [Smartsheet.Api.Models.Cell]::new()
$checkCell.ColumnId = $ptCheckCol.Id
$checkCell.Value = $orbitalRecord.Completed
$supCell = [Smartsheet.Api.Models.Cell]::new()
$supCell.COlumnId = $ptSupplierCol.Id
$supCell.Value = if (($orbitalRecord.Completed -eq $false) -and ($orbitalRecord.Supplier -eq "In Shop FAB")){$suppliers["$fabId"]} else {$suppliers["$DriveId"]}
$assignCell = [Smartsheet.Api.Models.Cell]::new()
$assignCell.COlumnId = $ptAssignCol.Id
$assignCell.Value = if ($orbitalRecord.Assign -ne $null){$orbitalRecord.Assign} else {"ianz#allnewglass.com"}
$finishedCell = [Smartsheet.Api.Models.Cell]::new()
$finishedCell.ColumnId = $ptFinishedCol.Id
$finishedCell.Value = $orbitalRecord.Check
$row = [Smartsheet.Api.Models.Row]::new()
$row.ToBottom = $true
$row.Cells = [Smartsheet.Api.Models.Cell[]]#($poCell,$jobsCell,$descCell,$checkCell,$supCell, $assignCell, $finishedCell)
try
{
$newRow = $client.SheetResources.RowResources.AddRows($ptId, [Smartsheet.Api.Models.Row[]]#($row))
foreach($attachment in $orbitalRecord.Attachments)
{
$file = Get-AttachmentFromSmartsheet -attachmentId $attachment.Id -sheetId $orbitalId
$result = Save-AttachmentToSheetRow -sheetId $ptId -rowId $newRow.Id -file $file.FullName -mimeType $attachment.MimeType
}
}
catch
{
Write-Error $_.Exception.Message
Write-Host ""
}
}
}
}
}
}
}
}
Write-Host "Loading Dlls"
Load-Dll ".\smartsheet-csharp-sdk.dll"
Load-Dll ".\RestSharp.dll"
Load-Dll ".\Newtonsoft.Json.dll"
Load-Dll ".\NLog.dll"
while($true)
{
Write-Host "Fab Log to Driver List to Product Tracker system starting up."
$DriveId = ""
$fabId = ""
$ptId = ""
$suppliers = #{
$fabId = "In Shop FAB";
$DriveId = "DRIVER CHECKLIST";
}
$token = ""
$smartsheet = [Smartsheet.Api.SmartSheetBuilder]::new()
$builder = $smartsheet.SetAccessToken($token)
$client = $builder.Build()
$includes = #([Smartsheet.Api.Models.SheetLevelInclusion]::ATTACHMENTS)
$includes = [System.Collections.Generic.List[Smartsheet.Api.Models.SheetLevelInclusion]]$includes
Write-Host "Loading Sheets"
$Drive = $client.SheetResources.GetSheet($DriveId, $includes, $null, $null, $null, $null, $null, $null);
$fab = $client.SheetResources.GetSheet($fabId, $includes, $null, $null, $null, $null, $null, $null);
$pt = $client.SheetResources.GetSheet($ptId, $includes, $null, $null, $null, $null, $null, $null);
Write-Host "Comparing Objects"
$DriveCOs = Get-DriverComparisonObjects $Drive
$fabCOs = Get-ComparisonObjects $fab
$ptCOs = Get-ComparisonObjects $pt
Write-Host "Identifying Driver Checklist Columns"
#NO SPACE... BODY CHARACTER LIMIT FOR STACK OVERFLOW
Merge-DriverChecklistWithProductTracker -orbitalRecords $DriveCOs -orbitalId $DriveId
Write-Host "Driver Checklist to Product Tracker finished."
Start-Sleep -Seconds 10
}
Trying to use runspaces to do some web scraping and database inserts. when trying to multithread the job, any more than a single thread causes database lock errors and my script to crash. I'm using adodb connection to an access database.
Function InsertToTable1 {
param ($database,$query,$col2,$col3,$col4,$col5,$col6,$col7,$col8,$col9,$col10,$col11)
$OpenStatic = 3
$LockOptimistic = 3
$Connection = New-Object -ComObject ADODB.Connection
$Connection.Open("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=$database")
$Recordset = new-object -ComObject ADODB.Recordset
$Recordset.open($query,$Connection,$OpenStatic,$LockOptimistic)
$Recordset.AddNew()
$Recordset.Fields.Item("col2") = $col2
$Recordset.Fields.Item("col3") = $col3
$Recordset.Fields.Item("col4") = $col4
$Recordset.Fields.Item("col5") = $col5
$Recordset.Fields.Item("col6") = $col6
$Recordset.Fields.Item("col7") = $col7
$Recordset.Fields.Item("col8") = $col8
$Recordset.Fields.Item("col9") = $col9
$Recordset.Fields.Item("col10") = $col10
$Recordset.Fields.Item("col11") = $col11
$Recordset.Update()
$Recordset.close()
$Connection.close()
}
$code = #"
Function InsertToTable1 {$(Get-Command InsertToTable1 | Select -expand Definition)}
"# #
$pool = [RunspaceFactory]::CreateRunspacePool(1,1) #[int]$env:NUMBER_OF_PROCESSORS+1
$pool.ApartmentState = "MTA"
$pool.Open()
$runspaces = #()
$scriptblock = {
......
InsertToTable1 $DB $Q1 $varState $varTown $varStreet $fullURL $varStyle $varModel $varDescription $varUseCode $varDate $varDate
......
}
foreach ($x in $xxxxx) {
$runspace = [PowerShell]::Create().AddScript($scriptblock).AddArgument($x).AddArgument($code)
$runspace.RunspacePool = $pool
# Add runspace to runspaces collection and "start" it
# Asynchronously runs the commands of the PowerShell object pipeline
$runspaces += [PSCustomObject]#{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
}
while ($runspaces.Status.IsCompleted -notcontains $true) {}
$results = #()
foreach ($runspace in $runspaces ) {
$results = $runspace.Pipe.EndInvoke($runspace.Status)
$runspace.Pipe.Dispose()
}
$pool.Close()
$pool.Dispose()
Is there a way to do something like that in a snippet : <?php if ([[+idx]]==1) echo "0";<?
Thank you.
If you need to get the value of a template variable, you can use this
$id = $modx->resource->get('id');//ID of current resource
$name = $modx->resource->get('pagetitle');//title of current resource
$val = $modx->resource->getTVValue('name_of_tv');//get tv value of current resource by name
$val = $modx->resource->getTVValue($tv_id);//get tv value of current resource by ID
To get idx of migx tv you need something like this -
<?php
$docid = $modx->resource->get('id'); // id of curent resource
$tvname = 'name_of_your_tv'; // change to yours
$tv = $modx->getObject('modTemplateVar', array('name' => $tvname));
$outputvalue = $tv->renderOutput($docid);
$items = $modx->fromJSON($outputvalue);
$idx = 0; // initialize idx
$output = array();
foreach ($items as $key => $item) {
$idx++; // increase idx
$output[] = print_r($item,1); // test output
}
$outputSeparator = "\n";
$o = implode($outputSeparator, $output); // implode output
return $o;
Taken from migx snippet https://github.com/Bruno17/MIGX/blob/master/core/components/migx/elements/snippets/snippet.getImagelist.php
since you are probably calling your snippet from the resource in question [are you?] you can just pass the idx to the snippet....
[[!callMySnippet? &idx=[[+idx]] ]]
then in your snippet:
$output = '';
$idx = $scriptProperties['idx'];
if ($idx==1) {
$output = "0";
}
return $output;
When writing queries or running through result sets, I'm constantly having to refer to fields as "field_id_X". I want to believe there is a saner way to go about this than defining a CONST for every field_id/name pair.
define(NAME_FIELD ,'field_id_3');
define(HEIGHT_FIELD, 'field_id_4');
foreach( $result as $row ){
$name = $row[NAME_FIELD]; // :(
}
Get an Array for field id's and names...
function getFieldReferences() {
$sql = "SELECT field_id, field_name
FROM exp_channel_fields
WHERE site_id = ".$this->EE->config->item('site_id');
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$finalResult = array();
foreach ($result as $row)
$finalResult[$row["field_id"]] = $row["field_name"];
return $finalResult;
} else {
return false;
}
}
Example conversion of a specific entry details $entry_id...
$sql = "SELECT exp_channel_data.*, exp_channel_titles.*, exp_channels.channel_name
FROM exp_channel_data, exp_channel_titles, exp_channels
WHERE exp_channel_data.entry_id = $entry_id
AND exp_cart_products.entry_id = $entry_id
AND exp_channel_titles.entry_id = $entry_id
LIMIT = 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$result = $result[0];
//### Get Field Titles ###
$fieldReferences = getFieldReferences();
//### Replace Field ID reference with name ###
foreach ($result as $key => $value) {
if (substr($key,0,9) == "field_id_") {
$result[$fieldReferences[substr($key,9)]] = $value;
unset($result[$key]);
}
if (substr($key,0,9) == "field_ft_")
unset($result[$key]);
}//### End of foreach ###
}
Convert Member fields to names based on specified member $id...
$sql = "SELECT m_field_id, m_field_name
FROM exp_member_fields";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$memberFields = $result->result_array();
$sql = "SELECT exp_member_data.*, exp_members.email
FROM exp_member_data, exp_members
WHERE exp_member_data.member_id = $id
AND exp_members.member_id = $id
LIMIT 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$rawMemberDetails = $result[0];
//### Loop through each Member field assigning it the correct name ###
foreach($memberFields as $row)
$memberDetails[ $row['m_field_name'] ] = $rawMemberDetails['m_field_id_'.$row['m_field_id']];
}
You could look up exp_channel_fields.field_name (or field_label) by the field_id you have from exp_channel_data.
This is the code of my export_to_excel helper:
function export_to_excel($query, $filename='exceloutput')
{
$headers = ''; // just creating the var for field headers to append to below
$data = ''; // just creating the var for field data to append to below
$obj =& get_instance();
$fields = $query->list_fields();
if ($query->num_rows() == 0) {
echo '<p>The table appears to have no data.</p>';
} else {
foreach ($fields as $field) {
$headers .= $field . "\t";
}
foreach ($query->result() as $row) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
header("Content-type: application/x-msexcel; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename.xls");
echo "$headers\n$data";
}
}
I get different results in localhost and on server. When I run the code in localhost, it outputs the proper result with no problem, but when I run the code on server, it gives the same result as in localhost, but it adds two more lines (excel rows) containing error as follows:
<br />
<b>Fatal error</b>: ob_start()
[< a href='ref.outcontrol'> ref.outcontrol</a>]:
Cannot use output buffering in output buffering display handlers in
<b>/home/username/public_html/Codeigniter_website/system/core/Exceptions.php</b>
on line <b>181</b><br />
Any solutions?
It's almost a large project and it's the only difference that I have seen between local and server.
The solution is to make sure output and parsing stops after the desired output.
The can be done by putting exit; after echo "$headers\n$data";