I have a problem where I am getting data from database and need to put that in an array. The array is associative and I am not sure about this practice so I thought I should ask the community. Is this the correct way of adding data to array? The array is for the radio buttons that will be provided to the helper class in prestashop. The array structure is important. This is the var_dump array structure which I have in $options_break2.
$options_value = array();
$options = array();
for($z=0; $z<sizeof($options_break2); $z++)
{
$options_value = array_push($options_value,
array(
"id" => $options_break2[$z],
"name" => $options_break2[$z],
"label" => $options_break2[$z],
)
);
}
$options = array_push($options, $options_value);
What I want is that the array should contain something like:
$example = array(
array(
'id_option' => 'some value',
'name' => 'some value',
),
array(
'id_option' => 'some value',
'name' => 'some value',
),
);
Actually you don't need to use array_push and array() if your PHP version is above 5.6, and you can improve your loop by using the foreach loop:
$options_value = [];
foreach ($options_break2 as $opt) {
$options_value[] = [
"id_option" => $opt, // some_value
"name" => $opt // some_value
];
}
$options = $options_value; // you don't really need this
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,
In this loop, i am iterating through an array and performing an API call each time. This works fine but I keep reading that using variable variables is not good practice. How could I rewrite this code without using them?
edit: I am not using an array because I have to pass the variables into another template along has other variables outside that array.
template( 'template-name', [ 'graphOne' => $graphOne, 'graphTwo' => $graphTwo, 'outsideVar' => $anothervalue ] );
<?php
// Array of categories for each graph
$catArray = [
'One' => '3791741',
'Two' => '3791748',
'Three' => '3791742',
'Four' => '3791748'
];
foreach ( $catArray as $graphNum => $cat )
{
// Hit API
$graph_results = theme( 'bwatch_graph_call', [
'project' => '153821205',
'category' => $cat
]
);
${"graph{$graphNum}"} = $graph_results;
// Outputs $graphOne, $graphTwo, $graphThree...
}
// Pass vars to template
template( 'template-name', [
'graphOne' => $graphOne,
'graphTwo' => $graphTwo,
'outsideVar' => $anothervalue ]
);
You can use PHP's array_merge when you make your template() call if you have multiple arrays with different key=>value pairs.
http://php.net/array_merge
Here is an example if you have multiple arrays (key=>value pairs) you want to pass to the template.
// Array of categories for each graph
$catArray = [
'One' => '3791741',
'Two' => '3791748',
'Three' => '3791742',
'Four' => '3791748'
];
// Array of category results
$catResult = [];
foreach ( $catArray as $graphNum => $cat )
{
// Hit API
$catResult['graph' . $graphNum] = theme( 'bwatch_graph_call', [
'project' => '153821205',
'category' => $cat
]
);
}
// Now you have an array of results like...
// $catResult['graphOne'] = 'result for One';
// $catResult['graphTwo'] = 'result for Two';
$otherArray1 = ['outsideVar' => $anothervalue];
$otherArray2 = ['somethingElse' => $oneMoreValue];
// Pass all arrays as one
template('template-name', array_merge($catResult, $otherArray1, $otherArray2));
I am struggling to get values added into the array at specific points.
What I am looking for is to create and empty array, take the resultset from the database and depending on whether they are global or local create the PHP array listed below. The problem is that no matter what I try I can't get the array to look like below.
Either values are being replaced, or arrays being replaced or values being added into wrong places
This is my empty array and I am trying to loop each resultset into the array and then how many sold in the day.
$test = array();
foreach($globalDatabase as $value)
{
$test['global'][] = array('name'=>$value->type, 'data' => array($value->day,$value->quantity) );
}
foreach($localDatabase as $value)
{
$test['local'][] = array('name'=>$value->type, 'data' => array($value->day,$value->quantity) );
}
This is what I need it to look like so that it ends up looking like this, which is the output format I need it to be in so it is compatible with highcharts
$test = array(
'global'=>array(
array(
'name'=>'CARS',
'data' => array(
array('mon',1),
array('tue',1)
)
),
array(
'name'=>'BIKES',
'data' => array(
array('mon',1),
array('tue',1)
)
),
array(
'name'=>'BOATS',
'data' => array(
array('mon',1),
array('tue',1)
)
),
),
'local'=>array(
array(
'name'=>'CARS',
'data' => array(
array('mon',1),
array('tue',1)
)
),
array(
'name'=>'BIKES',
'data' => array(
array('mon',1),
array('tue',1)
)
),
)
);
I take it that your data rows pulled from the table are 'flat', meaning each row has only a single value each for 'type', 'day', and 'quantity', with no nesting.
Going on that assumption, you may just need to group your data by common attributes similar to the following:
$databases = array('global'=>$globalDatabase, 'local'=>$localDatabase);
$workData = array('global'=>array(), 'local'=>array());
foreach($databases as $dbType=>$workDb)
{
foreach ($workDb as $value) {
if(!array_key_exists($value->type, $workData[$dbType])) {
$workData[$dbType][$value->type] = array();
}
$workData[$dbType][$value->type][] = array($value->day, $value->quantity);
}
}
$test = array();
foreach ($workData as $type=>$workRow) {
foreach ($workRow as $dataKey=>$dataRow) {
$test[$type][] = array('name'=>$dataKey, 'data' => $dataRow );
}
}
Let's say I have an array formatted like so:
$data = array(
'variables' => array(
'823h9fhs9df38h4f8h' => array(
'name' => 'Foo',
'value' => 'green'
),
'sdfj93248fhfhf88rh' => array(
'name' => 'Bar',
'value' => 'red'
)
)
);
Say I wanted to access the name & values of each array in the variables array. Surely you can access it just looping over the main variables array and not looping over each individual item array? Something like so?
foreach ($data as $k => $v) {
$name = $data['variables'][0]['name'];
}
I'm sure I'm missing something simple...
You can do
foreach ($data['variables'] as $k => $v) {
$name = $v['name'];
}
You can also try this
create a new array containing just the names..
$new_arr = array_column($data['variables'],'name' );
echo $new_arr[0].'<br/>';
echo $new_arr[1].'<br/>';
I have the following challenging array of associative arrays in php.
array(
(int) 0 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name1'
)
),
(int) 1 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name2'
)
),
(int) 2 => array(
'table' => array(
'venue' => 'venue2',
'name' => 'name3'
)
),
(int) 3 => array(
'table' => array(
'venue' => 'venue3',
'name' => 'name4'
)
)
)
I want to extract a list of relevant names out based on the venue. I would like to implement a function ExtractNameArray($venue) such that when $venue=='venue1', the returned array will look like array('name1', 'name2')
I have been cracking my head over this. I am starting with $foreach and am stuck. How can this be done in php? Thank you very much.
first, you have to pass the array with the data to the function
second, the name of the function should start with lower character (php conventions)
try this
function extractNameArray($array, $venue) {
$results = array();
foreach($array as $key=>$value) {
if(isset($value['table']['venue'])&&$value['table']['venue']==$venue) {
isset($value['table']['name']) && $results[] = $value['table']['name'];
}
}
return $results;
}
function ExtractNameArray($venue)
{
$array = array(); // your array
$return_array = array();
foreach($array as $arr)
{
foreach($arr['table'] as $table)
{
if($table['venue'] == $venue)
{
$return_array[]['name'] = $table['name'];
}
}
}
return $return_array;
}
You must define $array with you array. Good Luck