PHP Excel from array merge cells - php

I export a table of participants. I have a form for the participants, where I have dynamically generated section for choosing meals. It comes from array like this:
$days = array(
array(
'title' => 'Saturday',
'meals' => array(
array(
'title' => 'Brf',
'price' => 25
),
array(
'title' => 'Lnch',
'price' => 60
),
array(
'title' => 'Dnr',
'price' => 35
)
)
)
);
I need to merge and center day titles (Thursday, Friday...) and merge with number of cells on the right. The number of merged cells equals to count($days[$day]['meals']).
The goal looks like this:
I use creating table from array $PHPexcelsheet->from_array($a); for table data. If it could be used for the header too, would be nice, but not necessary.

Finally I got to the solution. Doesn't seem so pretty, as I supposed, and also doesn*t work with more than 26 cols (which I don't need), but works.
$i = 0;
$c = 4;
$alphabet = range('A', 'Z');
while ($i < count($ceny_jidlo)) {
$den = $ceny_jidlo[$i];
$s = $alphabet[$c];
$sheet->setCellValue("{$s}1", $den['short']);
$co = $c;
$c = $c + count($den['opts']) - 1;
$e = $alphabet[$c];
for ($j = $co; $j <= $c; $j++)
colstyle($shit, $alphabet[$j], $eRow, 10);
$sheet->mergeCells("{$s}1:{$e}1");
$c++;
$i++;
}

Related

How to count the number of item in foreach loop based by it's parent?

I have a simple loop to display a list. But I do not know how to count it's parent item. This is my current attempt:
$no = 0;
$ct = 0;
$type = "";
foreach($item as $row_item){
$no = $no + 1;
if($type != $row_item['type']){
$ct = $ct + 1;
}
echo $no." ".$row_item['type']." ".$row_item['item'];
$type = $row_item['type'];
}
My desired output :
1 TYPE_A 3 A1
2 TYPE_A 3 A2
3 TYPE_A 3 A3
4 TYPE_B 2 B1
5 TYPE_B 2 B2
In order to count the total number of each type you'll need to iterate over the entire collection twice. Once to count the totals, and once to display the results for each row. The code below actually does 3 loops, the array_filter method iterates over the entire array, but I like the clean code. :)
http://sandbox.onlinephpfunctions.com/code/962f418715d1518c818732f6e59ba4f28d5a19f3
<?php
$items = array(
array( 'name' => 'A1', 'type' => 'TYPE_A' ),
array( 'name' => 'A2', 'type' => 'TYPE_A' ),
array( 'name' => 'A3', 'type' => 'TYPE_A' ),
array( 'name' => 'B1', 'type' => 'TYPE_B' ),
array( 'name' => 'B2', 'type' => 'TYPE_B' )
);
function is_TYPE_A( $item ) {
return $item['type'] == 'TYPE_A';
}
function is_TYPE_B( $item ) {
return $item['type'] == 'TYPE_B';
}
$TYPE_A_COUNT = count( array_filter( $items, 'is_TYPE_A' ) );
$TYPE_B_COUNT = count( array_filter( $items, 'is_TYPE_B' ) );
function getTypeTotalByItem( $item ) {
global $TYPE_A_COUNT, $TYPE_B_COUNT;
if ( $item['type'] == 'TYPE_A' ) {
return $TYPE_A_COUNT;
}
if ( $item['type'] == 'TYPE_B' ) {
return $TYPE_B_COUNT;
}
}
for ( $i = 0; $i < count( $items ); $i++ ) {
echo ( $i + 1 )." ".$items[$i]['type']." ".getTypeTotalByItem($items[$i])." ".$items[$i]['name']."\n";
}
You can use array_map() and a couple foreach() loops for this if you were so inclined. It should interpret fairly quickly:
# Create a storage array
$counter = [];
# Sort the main array into type
array_map(function($v) use (&$counter){
# Store the subs under the type
$counter[$v['type']][] = $v['item'];
},$items);
# Start counter
$i = 1;
# Loop through each type
foreach($counter as $title => $row){
# Count how many are under this type
$count = count($row);
# Loop the rows in the types arrays
foreach($row as $item) {
# Write increment, type, total count, item
echo $i." ".$title." ".$count." ".$item.'<br />';
$i++;
}
}

Localize markers in PHP Array

This is quite basic, but I am missing a puzzle piece.
I have a multidimensional PHP array that - among other things - contains some strings. I would like to translate special strings in this array based on a translation table or array in PHP.
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
In $r, now I would like to replace {{animals}} with another string that is stored in a separate array.
Here it is:
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
Now let's set the language / column we want to look up
$langId = 0;
And now, take $r, look for all key that are wrapped in {{}}, look them up in $translations and replace them with key[$langId], so in return we get:
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 Tiere',
'anytext' => '400 Autos',
)
);
ehm... how's that done?
PS: the marker {{}} is random, could be anything robust
I was able to get the output you expected using the following code. Try it and tell me if it worked for you or not:
<?php
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
$langId = 0;
$pattern = "/\{\{[a-zA-Z]+\}\}/";
for($t=0; $t<count($r); $t++) {
$row = $r[$t];
if(!is_array($row))
continue;
foreach($row as $key=>$value) {
if(preg_match_all($pattern, $value, $match, PREG_SET_ORDER)) {
for($i = 0; $i < count($match); $i++) {
//remove {{ & }} to get key
$k = substr($match[$i][0], 2, strlen($match[$i][0])-4);
$replacer = $translations[$k][$langId];
$value = str_replace($match[$i][0], $replacer, $value);
$r[$t][$key] = $value;
}
}
}
}
?>

How do I retrieve a random value in multidimensional associative array?

I have an array which contains information on posts I have made.
$DexArray = array(
array(
'url' => "http://i.imgur.com/ObXLdd6C.jpg",
'headline' => "Dronningens Nytårstale",
'subline' => "Tallene bag talen og årets spilforslag",
'href' => "nytaarstale.php",
'postedby' => "kris",
'postedurl' => "https://www.facebook.com/dataanalyticsdk",
'dato' => "21. december, 2014"
),
array(
'url' => "http://i.imgur.com/sxddhOe.jpg",
'headline' => "Endless Jewelry",
'subline' => "Are there really endless possibilities?",
'href' => "endless.php",
'postedby' => "Nikolaj Thulstrup",
'postedurl' => "kris",
'dato' => "10. december, 2014"
),
It is stored in a multidimensional associate array. I am trying to retrieve a random 'href' value in the array and store it as a variable.
I have tried using the array_rand function but it doesn't seem to work.
$k = array_rand($DexArray);
$v = $array[$k]['href'];
I get an error message saying: undefined variable: array in this line "$v = $array[$k]['href'];"
Do you have a solution for this?
It should be
$k = array_rand($DexArray);
$v = $DexArray[$k]['href'];
Here's a working debug :) link
There was a lingering , in your thingy. And $array was never defined in the first place, so that's what the error was telling you about.
Execute the code it will return the random value from the multidimensional php array.
<?php
$filter_field = array();
$original_items = array(
array(1, 'stuff1', 'info1', 'response1', 'info1', 'response1'), array(2, 'stuff2', 'info2', 'response2', 'info2', 'response2'), array(3, 'stuff3', 'info3', 'response3', 'info3', 'response3'), array(4, 'stuff4', 'info4', 'response4', 'info4', 'response4'));
for ($x = 0; $x < sizeof($original_items); $x++) {
array_push($filter_field, $original_items[$x][0]);
}
shuffle($filter_field);
echo "<br/><br/><br/>";
for ($x = 0; $x < sizeof($original_items); $x++) {
$k = $filter_field[$x];
for ($y = 0; $y < 5; $y++) {
echo $original_items[$k-1][$y];
}
echo "<br/><br/>";
}
?>
Here is another solution that will return the index of the random array.
$var = array(
array("a", "one"),
array("b", "two"),
array("c", "three"),
array("d", "four"),
array("e", "five"),
array("f", "six"),
array("g", "seven")
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
print_r($finalVar);

JSON encoding from wordpress database values

I need a proper JSON file with "geo_langitude", "geo_latitude", "adress" & "url" values
I have wp database with post_meta "property" - "geo_langitude" "geo_latitude" & "address" in there.
my file is smth like that
<?php
function return_markers($count) {
$query = new WP_Query('post_type=property&posts_per_page=-1&orderby=menu_order&order=DESC&post_status=publish');
$array = array();
$i = 0;
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => get_post_meta($post->ID,'geo_latitude',true),
'y' => get_post_meta($post->ID,'geo_longitude',true),
'z' => $i
);
$array[] = $elem;
}
echo json_encode($elem);
};
return_markers($i);
?>
It's my first time using JSON so I have troubles and I don't know where. =(
with random markers work perfectly:
<?php
function return_markers($count) {
$array = array ();
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => 23 + (rand ( 0 , 10000 ) / 10000) * 5,
'y' => 56.2 + (rand ( 0 , 10000 ) / 10000) * 0.8,
'url' => '#map_redirect_'.$i,
'z' => $i
);
$array[] = $elem;
}
echo json_encode($array);
};
return_markers(23);
?>

Overlapping Associative Arrays

I need to overlap data from multiple associative arrays with the following considerations:
If a matching key exists, overwrite it
If a key exists but doesn't match, append new value to that element
If neither of the above, create an element to store the value
Take for example the following structures:
<?php
for ($i = 0; $i < 10; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 12,
'column' => 5
)
);
}
for ($i = 4; $i < 12; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 9,
'column' => 8
)
);
}
for ($i = 5; $i < 15; $i++) {
$table["table_$i"] = array(
"cell_1" => array(
'row' => 4,
'column' => 1
)
);
}
?>
The desired output would look like this:
{"table_0":{"cell_0":{"row":12,"column":5}},"table_1":{"cell_0":{"row":12,"column":5}},"table_2":{"cell_0":{"row":12,"column":5}},"table_3":{"cell_0":{"row":12,"column":5}},"table_4":{"cell_0":{"row":9,"column":8}},"table_5":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_6":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_7":{"cell_1":{"row":4,"column":1}},"table_8":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_9":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_10":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_11":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_12":{"cell_1":{"row":4,"column":1}},"table_13":{"cell_1":{"row":4,"column":1}},"table_14":{"cell_1":{"row":4,"column":1}}}
Take note from the desired output that the value of cell_0 doesn't replace the value of cell_1: I couldn't get the desired output using array_merge() in this case.
Any help would be appreciated--thanks!
Check array_merge and array_unique php functions.

Categories