Looping array error again :( - php

//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')));
?>

Related

How to use a while loop result within three dimensional array in php?

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,

Draw charts with a Loop using HighCharts in symfony

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);

Add a new field to array elements in a foreach PHP - Laravel

I have this variable:
$families = array(
array(
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
And I want add to my $families items a field called 'href', like this:
$families = array(
array(
'href' => 'http://mipage/wall-art/AAER',
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'href' => 'http://mipage/personalised-mug/EEER',
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
To do this I iterate $families in a foreach loop:
foreach($cat['families'] as $cat_fam) {
$cat['families'][]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
But this not works for me.
How can I make this?
You've to repalce empty [] with the specific key. For this update foreach block to get key of the element and use that inside foreach loop.
$cat['families'][$key] which points to individual element of the families array.
Like this,
foreach($cat['families'] as $key=>$cat_fam) {
$cat['families'][$key]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
Demo: https://eval.in/636898
just iterate over the array, and add a key ahref
$newArray= array();
foreach($families as $innerArray){
$innerArray['ahref']='YOUR LINK HERE';
$newArray[] = $innerArray;
}
$families = $newArray ;//if you want to update families array
Do something like:
$href = array('href'=>'http://mipage/wall-art/AAER');
$combined_array = array_combine($families[0],$href);
Don't tested but you can try or modify as per your use
Please try this:
I think you also forgot to add index description in your str_slug call.
foreach($cat['families'] as &$cat_fam) {
$cat_fam['href'] = 'http://mysite/'.str_slug($cat_fam['description']).'/'.$cat_fam['family_id'];
}
You can use the php function array_walk
Liek this :
array_walk($cat['families'], function(&$family){
$family['href'] = 'http//mysite/'.str_slug($family).'/'.$family['family_id'];
});
note the $family variable is passed by reference.

php create a new array from search results of another array

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);

Multidimensional array - search for same value

I have a multidimensional array which I am looping through using a foreach loop.
I have then need to check whether any of those arrays have the key of 'parent_page' and the same value of any other arrays, such as:
$arrMulti = array(array(
'page_id' => 1,
'page_parent' => 28,
'page_title' => 'Testing'
), array(
'page_id' => 2,
'page_parent' => 30,
'page_title' => 'A seperate page'
), array(
'page_id' => 3,
'page_parent' => 28,
'page_title' => 'Testing Sub Page'
));
So $arrMulti[0]['page_parent'] would match with $arrMulti[2]['page_parent'], so I need to then create a new array using those, something like this:
$arrParentIDs = array( 'parent_id' => array(
1,
3
));
Sorry for the poor explanation, but do you have any idea on how to do this?
Thanks!
$parentIds = array();
foreach($arrMulti as $temp):
if(isset($temp['page_parent'] && !in_array($temp['page_parent'], $parentIds)){
$parentIds[] = $temp['page_parent'];
}
endforeach;
var_dump($parentIds);//to show the contents
Try something like this..
foreach($arrMulti as $array) {
foreach($array as $key=>$val) {
//your statement/condition
}
}

Categories