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.
Related
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);
I am trying to assemble an array of objects from a variety of sources in PHP (I'm new to the language). The problem is that I am not able to store the data within the $bandwidthData array in the foreach loop I am trying to write.
private function _getData($startDay, $totalDays)
{
$devices = ubntDevices::getDevices();
$data = [];
$bandwidthData = [];
$count = 0;
foreach ($devices as $device) {
$bandwidthData[$count]['device'] = $device;
$bandwidthData[$count]['bandwidth'] = new ubntModel($device->file);
$bandwidthData[$count]['bandwidth']->getMonthData();
$bandwidthData[$count]['tree'] = new graphTree($device->hostid);
$bandwidthData[$count]['graphid'] = ubntGraph::getGraphByHostId($device->hostid);
$bandwidthData[$count]['hostname'] = $device->host_name;
$count++;
}
return $bandwidthData;
}
If I return from within the foreach loop, I get the correct output (but obviously for only the first device). I have tested all of the other function sources, and they seem to be returning the right data. Any idea what I could be doing wrong? Thank you in advance.
Your PHP error log should indicate what's going wrong. XDebug is very highly recommended as well.
However, nowadays it is more common to use an associative array like this:
private function _getData($startDay, $totalDays)
{
$devices = ubntDevices::getDevices();
$bandwidthData = [];
foreach ($devices as $device) {
$ubntModel = new ubntModel($device->file);
$deviceData = array('device' => $device,
'ubntModel' => $ubntModel,
'bandwidth' => $ubntModel->getMonthData(),
'tree' => new graphTree($device->hostid),
'graphid' => ubntGraph::getGraphByHostId($device->hostid),
'hostname' => $device->host_name);
$bandwidthData[] = $deviceData;
}
return $bandwidthData;
}
Some things I'm seeing:
Is this variable in use?
$data = [];
Also, this assignment runs but is a discouraged approach because at this point $bandwidthData[$count] does not exist:1
$bandwidthData[$count]['device'] = $device;
That can be converted to:
$bandwidthData[$count] = [ 'device' => $device ];
Also, this just a getter returning nowhere. Isn't it?
$bandwidthData[$count]['bandwidth']->getMonthData();
Also to further learn PHP I can suggest such cleaner approach for that code snippet, just to improve readability:
private function _getData( $startDay, $totalDays ) {
$bandwidthData = [];
foreach ( ubntDevices::getDevices() as $device ) {
$bandwidthData[] = [
'device' => $device,
'bandwidth' => new ubntModel( $device->file ),
'tree' => new graphTree( $device->hostid ),
'graphid' => ubntGraph::getGraphByHostId( $device->hostid ),
'hostname' => $device->host_name,
];
}
return $bandwidthData;
}
Anyway you have to learn how to debug that simple small block of code just looking at your server logs, or with a lazy var_dump( $bandwidthData[ $count ] ) in your suspected line (do not fight about this debugging approach: it's super stupid, but dramatically simple and effective, and friendly for newcomers - if you have not the possibility to setup a debugger because maybe the server is not yours etc.) or setting up a debugger.
1 from https://www.php.net/manual/en/language.types.array
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment
Sometime I need to create key in a array if it don't exist.
For example:
$dataAgent['Paul'] = array('Sale' => 4,'Conv' => 1.5);
$dataAgent['Bill'] = array('Sale' => 6,'Conv' => 5.5);
$dataAgent['Tom'] = array('Sale' => 1);
$dataAgent['Jake'] = array('Sale' => 6,'Conv' => 10.5);
'Conv' key is missing in $dataAgent['Tom'] array.
I use the following code to check if 'Conv' key exist:
foreach($dataAgent as &$agent) {
if (!isset($agent['Conv'])) {
$agent['Conv'] = 0;
}
}
Is there alternative way instead of using foreach and better readability?
You will have to loop through the array one way or another, the key is not going to magically appear in all elements at once. You can just dress up the operation differently. My favourite would probably be:
$dataAgent = array_map(function (array $data) { return $data + array('Conv' => 0); }, $dataAgent);
Note that the + operator makes the use of isset unnecessary here.
The following are the solutions:
Put this key while forming your array. OR
Use array_walk($Your_array, "your_function");
function your_function($value, $key)
{
// put your logic here.
}
for more info: http://in3.php.net/array_walk
First of all, my grouping is working but I feel it is dirty. Need someone to make it looks
clean and better.
I have following foreach
$data['new_array'] = array(); //I have to use $data['new_array'] because I need to pass it to template.
foreach ($get_topics as $topic) {
//Is that possible to make these 4 lines shorter?
$data['new_array'][$topic['tid']]['tid'] = $topic['tid'];
$data['new_array'][$topic['tid']]['title'] = $topic['title'];
$data['new_array'][$topic['tid']]['yes'] = $topic['yes'];
$data['new_array'][$topic['tid']]['no'] = $topic['no'];
//The belows are subarray grouping, it actually works but I need better solutions
//$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['vid'];
//$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['yesno'];
}
I wouldn't even try to make it shorter, but here's your code in a good looking version.
$data['new_array'] = array();
foreach ($get_topics as $topic) {
$data['new_array'][$topic['tid']] = array(
'tid' => $topic['tid'],
'title' => $topic['title'],
'yes' => $topic['yes'],
'no' => $topic['no']
);
}
Not sure what type is $topic['tid'] but you should be careful when using non-consecutive numbers as array keys.
$list = array(
[0]=> array(
[name]=>'James'
[group]=>''
)
[1]=> array(
[name]=>'Bobby'
[group]=>''
)
)
I am looking to update the item 'group' where the name is 'Bobby'. I am looking for a solution with the two following formats. Thank you in advance for your replies. Cheers. Marc.
array_push($list, ???)
and
$list[] ??? = someting
As far as I know, there's no way updating your array with one of the given syntax.
The only similar thing I can come on is looping over the array using array_walk ... http://www.php.net/manual/en/function.array-walk.php
Example:
array_walk($list, function($val, $key) use(&$list){
if ($val['name'] == 'Bobby') {
// If you'd use $val['group'] here you'd just editing a copy :)
$list[$key]['group'] = "someting";
}
});
EDIT: Example is using anonymous functions which is only possible since PHP 5.3. Documentation offers also ways working with older PHP-versions.
This code may help you:
$listSize = count($list);
for( $i = 0; $i < $listSize; ++$i ) {
if( $list[$i]['name'] == 'Bobby' ) {
$list[$i]['group'] = 'Hai';
}
}
array_push() doesn't really relate to updating a value, it only adds another value to an array.
You cannot have a solution that will fit both formats. The implicit array push $var[] is a syntactic construct, and you cannot invent new ones - certainly not in PHP, and not most (all?) other languages either.
Aside from that, what you are doing is not pushing an item on to the array. For one thing, pushing items implies an indexed array (yours is associative), and for another pushing implies adding a key to the array (the key you want to update already exists).
You can write a function to do it, something like this:
function array_update(&$array, $newData, $where = array(), $strict = FALSE) {
// Check input vars are arrays
if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE;
$updated = 0;
foreach ($array as &$item) { // Loop main array
foreach ($where as $key => $val) { // Loop condition array and compare with current item
if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) {
continue 2; // if item is not a match, skip to the next one
}
}
// If we get this far, item should be updated
$item = array_merge($item, $newData);
$updated++;
}
return $updated;
}
// Usage
$newData = array(
'group' => '???'
);
$where = array(
'name' => 'Bobby'
);
array_update($list, $newData, $where);
// Input $array and $newData array are required, $where array can be omitted to
// update all items in $array. Supply TRUE to the forth argument to force strict
// typed comparisons when looking for item(s) to update. Multiple keys can be
// supplied in $where to match more than one condition.
// Returns the number of items in the input array that were modified, or FALSE on error.