I try to write a string into a variable in between an array
if ($row_klasse['RabKlNummerVK'] != ''){
$headerrabklasse = '\'Rabatt\'\=\>\'price\'\,';
}
else {$headerrabklasse = '';}
then I want to write the variable $headerrabklasse in:
$writer = new XLSXWriter();
$writer->writeSheetHeader (Preisliste, array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
$headerrabklasse
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0] );
And I always get an error...
HAs anybody an idea?
In PHP you can easily append data to array like this:
//Define array with default values
//BTW: if you work with PHP >= 5.4 better to use [] instead of array()
$sheetHeaders = array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'
);
if ($row_klasse['RabKlNummerVK'] != ''){
//Here you append data to existing array in format: array[key] = value
$sheetHeaders['Rabatt'] = 'price';
}
//Then use fulfilled array as you want
$writer->writeSheetHeader ($preisliste, $sheetHeaders);
Your array takes keys and values, so you need to write a key name, and pass the variable as a value. I also noticed you were mixing Array declarations. In PHP you can call an array like this:
Array(el1, el2, ...)
or like this:
[el1, el1, ...]
Either one is fine, but for best practices you want to pick one and stick with it.
$writer->writeSheetHeader(Preisliste, [
'Marke'=>'string',
...
'MyNewKeyName' => $headerrabklasse,
...
],
[
...
]
);
I guess you wan't to do this one:
if ($row_klasse['RabKlNummerVK'] != '') {
$headerrabklasse = ['Rabatt' => 'price'];
}
else {$headerrabklasse = [];}
You could do stuff like that:
$writer->writeSheetHeader (Preisliste, array_merge(array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0]), $headerrabklasse);
Related
I have an assoc array looking like this (the data comes from user input, this is just an example)
$startingDate = "2020-10-20";
$daysBetween[] = "2020-10-21", "2020-10-22", "2020-10-23";
$endingDate = "2020-10-24";
$eventDates[ID] => [
"startingDate" => $startingDate,
"daysBetween" => $daysBetween,
"endingDate" => $endingDate,
];
How would I look for a specific startingDate for example if I don't want to loop over every ID. Basically I'm looking for a way to do something like $eventDates[*]["startingDate"]
You can achieve this a few different ways, one being array_filter().
$searchFor = '2020-09-20';
$result = array_filter($eventDates, function($v) use ($searchFor) {
return ($v['startingDate'] ?? null) == $searchFor;
});
This returns the array(s) where you match the $searchFor variable with a column startingDate. If you just want the first one, use $result = array_shift($result); to get the first one.
This approach basically filters out any results where the callback doesn't return true. By including use ($searchFor) the variable becomes visible inside the scope of that function, otherwise it would be undefined within that scope.
Live demo at https://3v4l.org/iaT8k
The questioner states that they are looking for a way to do something like
$eventDates[*]["startingDate"]
The PHP equivalent to this is:
foreach ($eventDates as $id => $eventDate) {
//look at $eventDate["startingDate"] and if it matches the criteria do whatever required
//you know the ID (=$id) so you can save/return/use that if needed.
}
I have a json response from backend like this:
[{"studentID":"1","subjectID":"2","marks":65},
{"studentID":"1","subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80},
{"studentID":"2","subjectID":"3","marks":82},
{"studentID":"3","subjectID":"2","marks":"82"},
{"studentID":"3","subjectID":"3","marks":"75"}]
but i want to have it like this:
[{"studentID":"1","subjectID":"2","marks":65,"subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80,"subjectID":"3","marks":82}
{"studentID":"3","subjectID":"2","marks":"82","subjectID":"3","marks":"75"}]
Any idea on how to achieve this from the given array?
As mentioned you can't have duplicate keys in each object. You need to rebuild it in to something you can use. Something like this maybe:
$data = json_decode('[{"studentID":"1","subjectID":"2","marks":65},{"studentID":"1","subjectID":"3","marks":75},{"studentID":"2","subjectID":"2","marks":80},{"studentID":"2","subjectID":"3","marks":82},{"studentID":"3","subjectID":"2","marks":"82"},{"studentID":"3","subjectID":"3","marks":"75"}]');
$students = [];
foreach($data as $d) {
// If entry for student does not exist, create it
if(!isset($students[$d->studentID])) {
$students[$d->studentID] = ["subjects" => []];
}
// Add data to correct subject
$students[$d->studentID]['subjects'][$d->subjectID] = [
"marks" => $d->marks
];
}
echo json_encode($students);
// Output is: {"1":{"subjects":{"2":{"marks":65},"3":{"marks":75}}},"2":{"subjects":{"2":{"marks":80},"3":{"marks":82}}},"3":{"subjects":{"2":{"marks":"82"},"3":{"marks":"75"}}}}
Then you could access your data with $students[studentID]['subjects'][subjectId]['marks']
I have those two arrays that I added to attachments.
"PartnerAffiliateCodeId" from first array and "Id" from second array is our primary key.
"UserAction" must be counted for every unique "PartnerAffiliateCodeId" so in our case it is 5.
Normally I think this must be done by SQL but unfortunately this is a API method that I am receiving so I have to handle it by PHP.
Any ideas about how I can make such join with PHP using these two arrays?
I'm unclear on exactly what you're trying to get at with UserAction, but you could try something like this:
//$array1 = the first array
//$array2 = the second array
array_push($array_1, array(
"DateTime" => "",
"HttpReferer" => "",
"Id" => count($array1),
"PartnerAffiliateCodeId" => $array2["Id"],
"UserAction" => "Click"
));
It sounds like you want to match the ID key to the PartnerAffiliateCodeId in your returned data set.
Without knowing your setup, or bothinging with total optimization here a workable solution which will give you some direction.
function selectPartnerWhere($id=null; $from=array())
{
$codes = array();
foreach($from as $k => $p)
{
if($id == $p['PartnerAffiliateCodeId'])
{
return $from[$k];
}
}
return array();
}
$theData = //your array above
$thePartner = //your partner above
$partnerData = selectPartnerWhere($thePartner['Id'], $theData);
Working with opencart and am trying to enter another value within the product session. By default it only brings ID. How can I get further information?
if (!in_array($this->request->post['product_id'], $this->session->data['wishlist'])) {
$this->session->data['wishlist'][] = $this->request->post['product_id'];
$this->session->data['wishlist'][] = $my_var;
}
If I read this correctly you are trying to add additional data to an already existing array...what you are looking for is
array_push();
array_push — Push one or more elements onto the end of array
syntax:
int array_push ( array &$array , mixed $value1 [, mixed $... ] )
example:
$array = array();
$addingthistoarray = "value to add";
array_push($array, $addingthistoarray);
I'm not sure exactly what you're looking for, but you should be able to do something like this (assuming your "$_SESSION"):
PHP session array
session_start();
$_SESSION['wishlist'] = array( ... );
...
$_SESSION['wishlist']['product_id'] = $this->request->post['product_id'];
...
This is probably a silly question:
I am doing the following to set the headers in an array that I convert to a CSV download. The CSV part is irrelevant to this question as it works just fine.
Array Headers:
$csv_fields = array();
$csv_fields[0] = array();
$csv_fields[0][] = 'Category';
$csv_fields[0][] = 'Question';
$csv_fields[0][] = 'Case';
$csv_fields[0][] = 'Partner';
// ... etc
Now I want to set the heads based on check boxes that are Posted to the script. I was going to use lots of if, else statements like so:
if ($_POST['category']) {
$csv_fields[0][] = 'Category';
elseif ($_POST['question']) {
$csv_fields[0][] = 'Question';
}
// .... etc
But thought there might be a better way using Ternary Operator. I tried the following, but of course if the $_POST is not set, it still adds a null value to the array, so I get gaps in my headers.
$csv_fields[0][] = isset($_POST['category']) ? 'Category' : NULL;
// ... etc
I end up with something like:
[0] =>
[1] => Question
[2] =>
[3] => Partner
// ... etc
So my question is, how can I use the Ternary Operator to just skip rather than set the array value if the $_POST variable is not set?
Or is there a better way?
Thanks
I don't think a tenary operator could help you with this..
But you could shorten your code, because it's a lot of boilerplate and you could move everything to an loop.
$vars = array(
'category' => 'Category',
// ...
);
foreach ($vars as $name => $text) {
if (isset($_POST[$name])) {
$csv_fields[0][] = $text;
}
}
You could use ternary in combination with array_merge().
$csv_fields[0] = array_merge($csv_fields[0],
isset($_POST['category']) ?
array('Category') : array());
It's neither pretty or efficient. Better use a loop.