I am currently using Highcharts in symfony. It works good when I enter static data (array1/array2/array3/array4) like this:
$ob1 = new Highchart();
$ob1->chart->renderTo('barchart');
$ob1->title->text('Chart 1');
$ob1->xAxis->categories($arrayResult);
$ob1->plotOptions->pie(array(
'allowPointSelect' => true,
'cursor' => 'pointer',
'dataLabels' => array('enabled' => false),
'showInLegend' => true
));
$ob1->series(array(array('type' => 'column','name' => 'bar1', 'data' => $array1),
(array('type' => 'column','name' => 'bar2', 'data' => $array2)),
(array('type' => 'column','name' => 'bar3', 'data' => $array3)),
(array('type' => 'column','name' => 'bar4', 'data' => $array4))
));
but what I need is to enter data within a loop because I have an irregular number of arrays. I tried this but I got an error "unexpected 'while' (T_WHILE)" Is there anything I have missed here?
Here is my code using while to add Chart's Data Series:
$i=1;
$number=4;
$ob1->series(array(
(
$myarray = array();
while($i <= $number): array_push($myarray, array(0 => 'value', 1=> $i));
$i++;
array('type' => 'column','name' => 'bar'.$i, 'data' => $myarray)
endwhile;
),
));
I also tried this and displays only the last iteration of the while
$i=1;
$number=4;
$myarray = array();
while($i <= $number):
array_push($myarray, array(0 => 'value', 1=> $i));
$i++;
$ob1->series(array (array('type' => 'column','name' => 'bar'.$i, 'data' => $myarray)));
endwhile;
Your php statement is not valid, has invalid syntax. To avoid this type of error, never create a loop inside the function argument. Simplify your syntax and use temporal variables, is easy to read and to understand what are you doing, remember, every good developer always say: "divide and conquer" :)
$i = 1;
$number = 4;
$chartData = [];
while ($i <= $number) {
$chartData[] = [
'type' => 'column',
'name' => 'bar'.$i,
'data' => [
'value',
$i,
],
];
$i++;
}
$ob1->series($chartData);
Related
I would like to pass a while loop result as a value to three dimensional array,i have tried but i couldn't get it.I am trying to solve this from few days.Any suggestions or answers are appreciated.Thank you
$messages = array(
'sender' => "akhil",
'messages' => array(
//////////////while loop starts
while($i < $data){
array(
'number' =>$data[$i],//////here i want to pass the while loop
variable
'text' => rawurlencode('Hello,.........')
)
$i++;
}
/////////////while loop ends
)
);
///the would like to get the below result
$messages = array(
'sender' => "akhil",
'messages' => array(
array(
'number' => 918xxxxxx,
'text' => rawurlencode('Hello,------')
),
array(
'number' => 9196xxxxxx,
'text' => rawurlencode('Hello,----')
)
), array(
'number' => 919xxxxx,
'text' => rawurlencode('Hello,----')
)
)
);
You just need to create the array outside the while loop and then push values into it inside the loop. Your code is almost there...
$messages = array('sender' => "akhil",
'messages' => array()
);
while ($i < count($data)) {
$messages['messages'][] = array('number' => $data[$i],
'text' => rawurlencode('Hello,.........'));
$i++;
}
Demo on 3v4l.org
What you are looking for is called an Anonymous function.
You can achieve your expected behavior by doing this:
'messages' => (function(){
$res = [];
while($i < $data){
$res[] = [
'number' =>$data[$i],//////here i want to pass the while loop variable
'text' => rawurlencode('Hello,.........')
];
$i++;
}
return $res;
})(),
...
I do not know the exact structure of your data, but I would swap the while for an array_map(). It would look like this:
'messages' => array_map(function($d){
return [
'number' =>$d,
'text' => rawurlencode('Hello,.........')
]
},$data),
...
Hohpe that helps,
$arr[] = array('title' => 'Overview');
$arr[] =array('title' => 'General');
$arr[] =array('title' => 'History');
$arr[] =array('title' => 'Construction');
$arr[] =array('title' => 'Plan');
$arr[] =array('title' => 'Other');
$info_arr[] = array("title" => "General", text => "value1");
$info_arr[] = array("title" => "History", text => "value1");
$info_arr[] = array("title" => "Construction", text => "value1");
$info_arr[] = array("title" => "Plan", text => "value1");
I need to be able merge these arrays together.So they look something like this. As I will need to loop thru the consolidated array. Other, Overview do not have any text values but still need to placed into the array.
$new_arr[] = array("title" => "General", text => "value1", "title" => "History", text => "value1", "title" => "Construction", text => "value1"
,"title" => "Plan", text => "value1","title" => "Overview", text => "","title" => "Other", text => "");
I have tried for loops (using count value), foreach loops, I thought array_intersect or array_diff don't see to solve the issue. This should not be so difficult, but I'm trying to piece together some really bad legacy code. Or the cube/florescent lights might have finally got to me.
Update:
while ($stmt->fetch()) {
$arr[] = array("title" => $Title);
}
and
while ($dstmt->fetch()) {
$info_arr[] = array("title" => $descriptionType, "descriptiontext" => $descriptionText); , "descriptiontext" => $val );
}
$dstmt & $stmt are queries.
I thought this would work but not so much
$r = array_intersect($arr, $info_arr);
var_dump($r);
Something like this Let me clarify:
$new_arr = array(array("title" => "General", text => "value1"),
array("title" => "History", text => "value1"),
array("title" => "Construction", text => "value1"),
array("title" => "Plan", text => "value1"),
array("title" => "Overview", text => ""),
array("title" => "Other", text => "")
);
If you want to work with these two arrays, you can just use the title as the key in $r.
foreach (array_merge($arr, $info_arr) as $x) {
$r[$x['title']]['title'] = $x['title'];
$r[$x['title']]['text'] = isset($x['text']) ? $x['text'] : '';
}
Or, you can go back a step and avoid having separate arrays by building the $r array in the same manner as you fetch your query results:
while ($stmt->fetch()) {
$r[$Title] = array('title' => $Title, 'text' => '');
}
while ($dstmt->fetch()) {
$r[$descriptionType] = array("title" => $descriptionType, "text" => $descriptionText);
}
Or, ideally, you could go back another step and avoid having separate queries by using a JOIN to get the same results in one query, but there's nothing in the question on which to base any specific suggestion for that.
As stated in the comments, the exact $new_arr you're requesting isn't possible. However, I think this will give you a similar result that should work for your purposes:
foreach ($info_arr as $infoArray) {
$found = array_search(array('title' => $infoArray['title']), $arr);
if (false !== false) {
unset($arr[$found]);
}
}
$new_arr = array_merge($info_arr, $arr);
It works by removing the "duplicates" from the original $arr before doing the array_merge().
If it's important to add an empty text value for the remaining items in $arr, do this before the array_merge():
foreach ($arr as &$arrArray) {
$arrArray['text'] = '';
}
The resulting array will look like this:
$new_arr[] = array(
array(
'title' => 'General',
'text' => 'value1',
),
array(
'title' => 'History',
'text' => 'value1',
),
array(
'title' => 'Construction',
'text' => 'value1',
),
array(
'title' => 'Plan',
'text' => 'value1',
),
array(
'title' => 'Overview',
'text' => '',
),
array(
'title' => 'Other',
'text' => '',
),
);
I never used generators in PHP. I understand the way to use it :
Foreach an array to do some tasks for each value like greping a specific line into a big file to remove some caracteres..
What I need :
I need to retrieve all bands from my dabatase. Sure I have the 'limit' argument to don't exceed the PHP's memory (there're 30 000 bands..).
I have to filters values and return a new array to the client into my REST API.
What I want to know :
Is it interesting for me to create a method into a trait called 'generator' to perform the code bellow ?
In all cases, I have to create a new array to return it into my method
$bands = Models\Bands::find($bandsParameters);
$json = [];
foreach ($bands as $band) {
$followers = $band->getFollowers();
$followersArr = [];
foreach ($followers as $follower) {
$followerImage = $follower->getImage();
$followerObj = (object)[
'id' => $follower->id,
'username' => $follower->username,
'image' => $followerImage->url,
'online' => $follower->online,
'createdOn' => $follower->createdOn,
'updatedOn' => $follower->updatedOn,
'lastLogin' => $follower->lastLogin,
];
$followersArr[] = $followerObj;
}
$info = $band->getInfo($bandInfoParameters)->getFirst();
$bandObj = (object)[
'id' => $band->id,
'name' => $band->name,
'style' => $band->styles,
'country' => $band->country,
'summary' => isset($info->summary) ? $info->summary : null,
'followers' => $followersArr,
'createdOn' => $band->createdOn,
'updatedOn' => $band->updatedOn,
'authoredBy' => $band->authoredBy,
'updatedBy' => $band->updatedBy,
];
$json[] = $bandObj;
}
return ['key' => 'bands', 'value' => $json];
//i want to loop an array to make dinamic chart
//form this
$this->widget('ext.Hzl.google.HzlVisualizationChart', array('visualization' => 'LineChart',
'data' => array(
0=>array('Task', 'Hours per Day'),
1=>array('Work', 11),
2=>array('Work', 11),
),
'options' => array('title' => 'My Daily Activity')));
?>
//to
$a=0;
$loop=array();
while ($a < 10)
{
$loop=$loop+array("a","1");
$a=$a+1;
}
$this->widget('ext.Hzl.google.HzlVisualizationChart', array('visualization' => 'LineChart',
'data' => $loop
'options' => array('title' => 'My Daily Activity')));
?>
//but this code is error, please help me :(
I assume you want $loop to be an array similar to the first example.
You need to change this:
$loop=$loop+array("a","1");
to this:
$loop[] = array("a","1");
This will add a new element to the array instead of overwriting it.
You can use:
$loop[] = array("a","1"); to add elements to the existing array.
And you are missing a comma after the 'data' => $loop
Try using:
$a=0;
$loop=array();
while ($a < 10)
{
$loop[] = array("a","1"); // "a" or $a ?
$a=$a+1;
}
$this->widget('ext.Hzl.google.HzlVisualizationChart', array('visualization' => 'LineChart',
'data' => $loop,
'options' => array('title' => 'My Daily Activity')));
?>
My initial array is
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
I am trying to create a new array based on the search results of another array so the new array should look like this if I search for 'crafts':
$employees2 = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'brad',
'area' => 'crafts')
);
What is the simplest solution I can do get get this new result.
foreach($employees as $key => $value){
if($value['area']=='crafts'){
$employees2[] = $value;
}
}
This quite simply loops through the first array and checks the value of "area" in the internal array. If the value is equal to "crafts" you can then put that into a new array which is called $employees2. You can change crafts to whatever you want and add anything you want between the [ ] in employees2 if you wish to customise the key.
Try this:
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees2 = array();
foreach ($employees as $key) {
if($key['name'] == "jack")
{
array_push($employees2,array('name'=>$key['name'],'area'=>$key['area']));
}
}
var_dump($employees2);
The array_push do all the trick ;)
Saludos.
You could simplify the syntax (but not the algorythmic complexity) by using a utility-belt library Underscore.php (http://brianhaveri.github.com/Underscore.php/)
There's a number of array-"plucking" methods that saves you the need to write loops, but under the bonnet it does much of the same as decribed in answers above.
I will assume that the possible result set can be large. In which case you would want to process the array with as little extra memory as possible. For this I suggest iterating through the array by reference and unsetting the items that do not match your criteria. Possibly less overhead than creating a new array to store the items that match your filter. Then you can check if the array is empty or not to determine if the filter returns any results. Like so:
<?php
// maybe this will be set through an option from the UI
$area_filter = 'crafts';
// fetched results
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
// filter out the items that match your filter
foreach($employees as $i => &$employee){
if($employee['area'] != $area_filter){
unset($employees[$i]);
}
}
// do something with the results
if(!empty($employees)){
print_r($employees);
} else {
echo "Sorry, your filter '$area_filter' did not match any results\n";
}
?>
Try this :
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees = array_filter($employees, function($employee) {
return ($employee['area'] == 'crafts' );
});
echo "<pre>";
print_r($employees);