PHPEXCEL : php excel only show 1 letter - php

Please help me on the PHPEXCEL. it shows only one letter.
this is my php code:
$sql_question = "SELECT * FROM tna_question WHERE title_id = '$tid' ORDER BY section_id";
$result_question = mysql_query($sql_question, $db);
$category = array();
while ($row = mysql_fetch_assoc($result_question)) {
$arr1 = $row['question'];
$arr = array_push($category ,$arr1);
$category_count++;
}
$arr3[] = $category;
the result from the sql query is an array:
Array ( [0] => gfhgfh [1] => gfhfg [2] => fggfdg [3] => fds [4] => asd [5] => fghgfh [6] => Policy Wordings / Coverage [7] => Risk Assessment / Survey & Underwriting [8] => Policy Wordings / Coverage [9] => Risk Assessment / Survey & Underwriting )
when i use this line:
$objPHPExcel->setActiveSheetIndex()->fromArray($category, NULL, 'C7');
it gives me only the first letter from each row
but if i make this one:
$objPHPExcel->setActiveSheetIndex()->fromArray($arr3, NULL, 'C7');
it'll give all the data in one row.
but The output that i want is like this:

You can use the below code to get the desired result :
foreach($arr3 as $k => $v){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $k, $v);
}
Note : Changing the column value will make it go left and right only. In case you want to shift the entire thing down then replace $k by $k+$val where $val is the number of rows you want to shift down.

Related

Numeric arrays with the same value

I have a function for dropdown list, which shows me the names for filtering results from two different queries. The one with the numeric value from 1-4 and the other with 10-110, some of the results have the same strings:
function filter_workhires($status) {
$status = array();
$status[1] = 'booked';
$status[70] = 'booked';
$status[2] = 'partiallyattended';
$status[90] = 'partiallyattended';
$status[3] = 'fullyattended';
$status[100] = 'fullyattended';
$status[4] = 'notattended';
$status[80] = 'notattended';
$status[10] = 'status_user_cancelled';
$status[20] = 'status_session_cancelled';
$status[30] = 'status_declined';
$status[40] = 'status_requested';
$status[50] = 'status_approved';
$status[60] = 'status_waitlisted';
$status[110] = 'status_not_set';
return $status;
}
In this form, I get double names for examle booked. How to combine the statuses according to the strings they show?
return array_unique($status);
That's about it :)
Output
Array
(
[1] => booked
[2] => partiallyattended
[3] => fullyattended
[4] => notattended
[10] => status_user_cancelled
[20] => status_session_cancelled
[30] => status_declined
[40] => status_requested
[50] => status_approved
[60] => status_waitlisted
[110] => status_not_set
)
Change it around so the description is the array key and the ID of the status is the value. When you build the array and you hit a duplicate you can then add multiple ID's to the value in some kind of structure like a comma separated string. So you end up with:
$status['booked'] = '70';
$status['partiallyattended'] = '2, 90';
$status['fullyattended'] = '3, 10';
...
When someone chooses an item you explode the value and get all the ID's that relate to that status.

PHP Regex removing unwanted values from pattern

I have a large array of scraped names and prices similar to the following:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [4] => lemon [5] => grape [6] => pear5 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
I would like to remove the fruit names that are not immediately followed by a price. In the above example this would remove: [4] => lemon [5] => grape [6] => pear5 resulting in the following output:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
If the array needs to be converted to a string in order for me to do this that is not a problem, nor is adding values between the array items in order to aid with regex searches. I have so far been unable to find the correct regular expression to do this using preg_match and preg_replace.
The most important factor is the need to maintain the sequential order of the fruits and prices in order for me at a later stage to convert this into an associative array of fruits and prices.
Thanks in advance.
Why involve regular expressions? This is doable with a simple foreach loop wherein you iterate over the array and remove names that follow names:
$lastWasPrice = true; // was the last item a price?
foreach ($array as $k => $v) {
if (ctype_alpha($v)) {
// it's a name
if (!$lastWasPrice) {
unset($array[$k]); // name follows name; remove the second
}
$lastWasPrice = false;
}
else {
// it's a price
$lastWasPrice = true;
}
}
The following code does both of your tasks at once: getting rid of the fruit without value and turning the result into an associative array of fruits with prices.
$arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );
preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
$final = array_combine( $pairs[1], $pairs[2] );
print_r( $final );
First, the array is converted to a string, separated by '#'. The regex captures all groups of fruits with prices - each stored as a separate subgroup in the result. Combining them into an associative array is a single function call.
Something like this might help you
$array = ...;
$index = 0;
while (isset($array[$index + 1])) {
if (!is_fruit($array[$index + 1])) {
// Not followed by a fruit, continue to next pair
$index += 2;
} else {
unset($array[$index]); // Will maintain indices in array
$index += 1;
}
}
Not tested though. Also, you need to create the function is_fruit yourself ;)
Without reformatting it, I don't think you can do it with preg_match or preg_replace-- maybe, but nothing is coming to mind.
What is creating that array? If possible, I would alter it to look more like:
Array([apple] => £0.40 [banana] => £1.80 [lemon] => [grape] => '' [pear ] => '' [melon => £2.32 [kiwi] => £0.50)
Then array_filter($array) is all you'd need to clean it up. If you can't alter the way the original array is created I'd lean towards creating key/value array out of the original.
Try replacing the pattern ** => ([a-zA-Z])** with ** => £0.00 $1**
Basically searching for the context where there is null price and inserting zero pounds.
Hope this helps.
Good luck
Simply do this :
<?php
for($i=0;$i<count($my_array);$i++)
{
if($my_array[$i+1]value=="")
unset($my_array[$i])
}
?>
assume $a is your array.
function isPrice($str) {
return (substr($str, 0, 1) == '£');
}
$newA = array();
for($i=0;$i<count($a);$i++) {
if( isPrice($a[$i]) != isPrice($a[$i+1]) ){
$newA[] = $a[$i];
}
}

PHP how to loop through an array and grab specific parts

Ok so im trying to grab a single part of an array, the array is the return for some stats there can be up to 8 players in the server, the data i get is like this
Array (
[0] => 1
[1] => Player1
[2] =>
[3] => 1
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 1
[9] => Player2
[10] =>
[11] => 1
[12] => 0
[13] => 0
[14] => 0
[15] => 0
)
so that is the return for 2 players, as i said it can be up to 8, anyway i am trying to just grab the player names and im not sure how to go about it ( Player1 , Player2 ) is the only data i need, any help is appreciated, it always returns 8 pieces of data per player never more never less if that makes it easier
(sorry for bad english)
If you have control over the return type, I would restructure the array being returned either into an Object or an array of arrays where each sub array contains all of the information for one player.
I you don't have control over the return type and the Player's name is always in the second position within the return array you can use a while loop to iterate over the array. Use a counter starting at 1 and then increment the counter by 8 each time through the loop. For example:
$i= 1;
while ($i < count($return_var)) {
$name = $return_var[$i];
// do something w/ name
$i += 8;
}
You want to get all items that are not '' (assuming empty string), 0 or 1 (assuming integers here):
$playerNames = array_diff($array, array('', 0, 1));
If you more specifically know what the format of the array actually is, you can also create some little "parser":
$playerSize = 8;
$playerFields = array('_1', 'name', '_3', '_4', '_5', '_6', '_7', '_8');
$players = array_chunk($array, $playerSize);
foreach($players as &$player)
{
$player = (object) array_combine($playerFields, $player);
}
unset($player);
This does parse $array into another array $players that contains one object per each player. Each object has the name property now:
printf("%d Player(s):\n", count($players));
foreach($players as $i => $player)
{
printf("#%d: %s\n", $player->name);
}
if the array you pasted is called $array and the values of the places without players are always numeric (like your example), this code will work:
$players = array();
foreach($array as $player){
if(!empty($player) && !is_numeric($player){
$players[]=$player;
}
}
var_dump($players);

If value exists in one PHP array, add value to second array

I have two PHP arrays. One contains a group name and another contains a pay wage value.
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 3 );
This means there are four employees on the schedule. Two are assigned to group 1, another to group 4 and the last to group 3.
The second array is as follows:
$tot_wages_array = Array ( [0] => 500 [1] => 44 [2] => 80 [3] => 11.25 );
This is a sample array of each employee's wage. Both arrays are constructed in order as values are added in a mysql while loop as it pulls the info from the database.
Later on down the line, I combine the two arrays to get one array where the key is the group number and the value is the total wages for that group:
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
This works like a charm EXCEPT for when more than one employee is assigned to the same group. These arrays are built in a mysql while loop as it loops through each employee's info:
array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array
Instead of just pushing the data to the array, I need to do this... I know the english but I don't know how to code it:
If $emp_data['group_id'] exists as value in $group_wages_array, add nothing to this array but get the key. Add $totemp_wages_sch to $tot_wages_array where key = group_wages_array key
I know it sounds more like an SQL query but I have to keep the keys and values in order so that they can be combined later in the page. If I can get this to work right, The arrays shown in the example would be:
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 3 );
$tot_wages_array = Array ( [0] => 580 [1] => 44 [2] => 11.25 );
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
$combined_group_wages = Array ( [1] => 580 [4] => 44 [3] => 11.25 );
...I've got to make this work using PHP. Any ideas?
I came up with a solution based on a combination of two of the answers submitted below. Here it is if it can help someone:
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] += $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
array_push($tot_wages_array, $totemp_wages_sch);
}
This should do it:
$group_wages_array = array(1, 4, 1, 3);
$tot_wages_array = array(500, 44, 80, 11.25);
$combined_group_wages = array();
for ($i=0; $i<count($group_wages_array); $i++) {
$group = $group_wages_array[$i];
if (array_key_exists($group_wages_array[$group], $combined_group_wages)) {
$combined_group_wages[$group] += $tot_wages_array[$i];
} else {
$combined_group_wages[$group] = $tot_wages_array[$i];
}
}
print_r($combined_group_wages);
Yields:
Array
(
[1] => 580
[4] => 44
[3] => 11.25
)
But I recommend that you just switch to using objects to better represent your data.
If I could see the entirety of the code that would help a lot, but here's your English converted to php. Show me more code and I can perfect it, until then try this ->
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] = $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
}

Remove duplicate values from Array

I can not "remove" the double values ​​from an array even if I use the function array_unique!
<?php
$tags_array = array() ;
$query_tags = $mysql->Query("SELECT words AS kw FROM users ") ;
/****
*
* This query return something like Array([1] => PHP,ASP,NET [2] => Ruby,Jquery,php,asp_net [3] => Php,asp,visualbasic,c# [4] => [5] =>)
*
*****/
while($fetch_tags = $mysql->Fetch($query_tags))
{
foreach(explode(',',$fetch_tags['kw']) as $kw => $value)
{
if(empty($value)) ;
else
{
$value = ucwords(strtolower($value)) ;
$tags_array[] = $value ;
}
}
}
$tags_array = array_values(array_unique($tags_array, SORT_STRING)) ;
print_r($tags_array) ;
/******
*
* print_r show somethings like this Array([1] => Asp [2] => Php [3] => Php [4] => Ruby [5] => Jquery [6] => Php [7] => Asp_net [8] = >C# [9] => Asp)
*
* IT'S ONLY AN EXAMPLE TO SHOW YOU THE SITUATION
*****/
?>
Make sure that the returned values are in fact not unique. For example
$foo = array("PHP","php","pHP","PHP ");
$foo = array_unique($foo);
Will still contain 4 entries.
If any entries contain spaces you should trim these.
Just use values as keys, they can only exist once and you don't have any numbers as your keywords (hopefully):
$tags_array = array_keys(array_flip(($tags_array));
array_flip will use values as keys (and drop duplicate values) and array_keys will then return all keys as values again.
Given that is the only thing that aray_unique is supposed to do, I find it very surprising it's not doing it. What is apparent from your post, is that maybe you think 'php' is the same thing as 'PHP'?
When I try the following I get unique results:
$d=Array('PHP,ASP,NET','Ruby,Jquery,php,asp_net','Php,asp,visualbasic,c#');
$o=array();
foreach ($d as $i) {
$p=explode(',',$i);
foreach ($p as $q) {
$o[]=strtoupper($q);
}
}
print_r(array_unique($o));
However the issue only arises because your database schema is not normalised.
As no one seemed to have provided the right answer, I'll repeat my comment here:
It might be that the words have preceding or trailing white spaces. Then they will never be equal to each other. You can remove these white spaces with trim [docs]
$value = ucwords(strtolower(trim($value)));

Categories