i want to loop all the data i call but that runs only one data
I use Codeigniter framework
Model:
$this->db->where('group_user', 'upt_perpus')->order_by('idmodul', 'DESC')->get('menu')->result_array();
Controller:
$data = array(
'about' => array(
'sejarah' => 'Sejarah',
'visi_misi' => 'Visi, Misi & Tujuan',
'struktur' => 'Struktur Organisasi'
),
'services' => array(),
'peraturan' => array(
'umum' => 'Umum',
'khusus' => 'Khusus',
'pelayanan_perpus' => 'Pelayanan Perpustakaan'
)
);
$konten = $this->kontens->getPerpus();
foreach ($konten as $key) {
$data['services'] = array(
$key['slug'] => $key['judul']
);
}
return $data;
If you want an associative array in $data['services'], you need to assign to a key of the array.
foreach ($konten as $key) {
$data['services'][$key['slug']] = $key['judul'];
}
Related
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 );
}
}
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
Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
The - (hyphen) symbol only illustrates the deep level.
Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.
EDIT
The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.
Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:
function generateDropdown($array, $level = 1)
{
if ($level == 1)
{
$menu = '<select>';
}
foreach ($array as $a)
{
if (is_array($a))
{
$menu .= generateDropdown($a, $level+1);
}
else
{
$menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
}
}
if ($level == 1)
{
$menu = '</select>';
}
return $menu;
}
OK, I got it with the help of #jmgardhn2.
The data
This is my array:
$temp = array(
array(
'name' => 'fruits',
'sons' => array(
array(
'name' => 'green',
'sons' => array(
array(
'name' => 'mango'
),
array(
'name' => 'banana',
)
)
)
)
),
array(
'name' => 'cars',
'sons' => array(
array(
'name' => 'italy',
'sons' => array(
array(
'name' => 'ferrari',
'sons' => array(
array(
'name' => 'red'
),
array(
'name' => 'black'
),
)
),
array(
'name' => 'fiat',
)
)
),
array(
'name' => 'germany',
'sons' => array(
array(
'name' => 'bmw',
)
)
),
)
)
);
Recursive function
Now, the following function will provide an array with items like [level] => [name]:
function createSelect($tree, $items, $level)
{
foreach ($tree as $key)
{
if (is_array($key))
{
$items = createSelect($key, $items, $level + 1);
}
else
{
$items[] = array('level' => $level, 'text' => $key);
}
}
return $items;
}
Calling the funcion
Now, call the function as below:
$items = createSelect($temp, array(), 0);
Output
If you iterate the final $items array it will look like:
1fruits
2green
3mango
3banana
1cars
2italy
3ferrari
4red
4black
3fiat
2germany
3bmw
So my example inputs are
$example_1 = Array (
0 => Array (
'category' => 'body',
'sub-category' => 'intro',
'id' => 'header',
'copy' => 'Hello',
),
1 => Array (
'category' => 'body',
'sub-category' => 'intro',
'id' => 'footer',
'copy' => 'Bye',
),
);
$example_2 = Array (
0 => Array (
'category' => 'body',
'sub-category' => 'intro',
'sub-sub-category' => 'header',
'sub-sub-child-category' => 'left',
'id' => 'title',
'copy' => 'Hello',
),
1 => Array (
'category' => 'body',
'sub-category' => 'intro',
'sub-sub-category' => 'footer',
'sub-sub-child-category' => 'right',
'id' => 'title',
'copy' => 'Bye',
),
);
I want to transform it into
$example_output_1 = Array (
'body' => Array (
'intro' => Array (
'header' => Array (
'title' => 'Hello',
),
'footer' => Array (
'title' => 'Bye',
),
),
),
);
$example_output_2 = Array (
'body' => Array (
'intro' => Array (
'header' => Array (
'left' => Array (
'title' => 'Hello',
),
),
'footer' => Array (
'right' => Array (
'title' => 'Bye',
)
),
),
),
);
Note the depth of the array is dynamic (it is not set - only by the time it hits 'copy' does it indicate the depth of the array).
I am having problems trying to get the recursion correctly. The basic but very rough algorithm I had was to
- Loop through the Row
- Loop through the contents of the Row
- When the index is "copy" then the final value is current value.
- Then build the array
I managed to get it to process for ONLY one row of the array but it was very messy and kinda patchy, so I got a feeling I really need to start from scratch.
Updated: Attached embarrassing Code as requested (don't scream! ;p)
function buildArray($row, $start = true) {
if ($start) {
$result = array();
}
if ( ! is_array($row) ) {
return $row;
}
// Get the first element of the array include its index
$cellValue = null;
$colId = null;
foreach($row AS $index => $value) {
$cellValue = $value;
$colId = $index;
break;
}
// Reduce the array by one
$tempRow = $row;
$temp = array_shift($tempRow);
if ($colId == 'copy') {
$result[$cell] = buildArray($cellValue, $locale, false);
} else {
$result[$cell] = buildArray($tempRow, $locale, false);
}
return $result;
}
Any help will be greatly appreciated.
Should be pretty straightforward:
$originalArray = array(); // <-- should contain your values
$newArray = array();
foreach( $originalArray as $item )
{
$category = $item['category'];
$subcategory = $item['sub-category'];
if ( empty( $newArray[$category] ) )
{
$newArray[$category] = array();
}
if ( empty( $newArray[$category][$subcategory] ) )
{
$newArray[$category][$subcategory] = array();
}
$newArray[$category][$subcategory][$item['id']] = $item['copy'];
}
See it here in action: http://codepad.viper-7.com/9bDiLP
Update: Now that you've specified that you need unlimited recursion, here's a shot at that:
$originalArray = array(); // <-- Your values go here
$newArray = array();
foreach ( $originalArray as $item )
{
$inception = &$newArray; // http://www.imdb.com/title/tt1375666/
foreach ( $item as $key => $val )
{
if ( $key != 'id' )
{
if ( empty($inception[$val]) )
{
$inception[$val] = array();
}
$inception = &$inception[$val];
}
else
{
$inception[ $val ] = $item['copy'];
break;
}
}
}
...and here's the demo: http://codepad.viper-7.com/F9hY7h
This can be solved iteratively, because the recursion would only happen at the tail end of your function. The following code is the simplification. It builds a new layered array while it iterates over the old.
After transforming each each entry it gets merged using array_merge_recursive.
function transform($a)
{
// create new array and keep a reference to it
$b = array(); $cur = &$b;
foreach ($a as $key => $value) {
if ('id' === $key) {
// we're done, add value to the array built so far using id and copy
$cur[$value] = $a['copy'];
break;
} else {
// create one more level
$cur[$value] = array();
// and update the reference
$cur = &$cur[$value];
}
}
// all done
return $b;
}
// $example_2 is your multi-dimensional array
$merged = call_user_func_array('array_merge_recursive',
array_map('transform', $example_2)
);
Official PHP documentation states that filter_var_array() supports array filtering in the following format:
$data = array(
'testarray' => array('2', '23', '10', '12')
);
$args = array(
'testarray' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY
)
);
$myinputs = filter_var_array($data, $args);
However, if the array in question is multi-dimensional and requires different filters for different parts, how would you approach defining filtering options?
As an example:
$data = array(
'testhash' => array('level1'=>'email',
'level2'=> array('23', '10', '12'))
);
Idea 1
Consider using FILTER_CALLBACK. In this way, you can write a callback function that itself uses the filter extension, thus providing a recursive ability.
function validate_array($args) {
return function ($data) use ($args) {
return filter_input_array($data, $args);
};
}
This will generate the callback functions.
$args = array(
'user' => array(
'filter' => FILTER_CALLBACK,
'options' => validate_array(array(
'age' => array('filter' => FILTER_INPUT_INT),
'email' => array('filter' => FILTER_INPUT_EMAIL)
))
)
);
This is what the config array would then look like.
Idea 2
Do not hesitate to pat me on the back for this one because I am quite proud of it.
Take an arg array that looks like this. Slashes indicate depth.
$args = array(
'user/age' => array('filter' => FILTER_INPUT_INT),
'user/email' => array('filter' => FILTER_INPUT_EMAIL),
'user/parent/age' => array('filter' => FILTER_INPUT_INT),
'foo' => array('filter' => FILTER_INPUT_INT)
);
Assume your data looks something like this.
$data = array(
'user' => array(
'age' => 15,
'email' => 'foo#gmail.com',
'parent' => array(
'age' => 38
)
),
'foo' => 5
);
Then, you can generate an array of references that map keys such as 'user/age' to $data['user']['age']. In final production, you get something like this:
function my_filter_array($data, $args) {
$ref_map = array();
foreach ($args as $key => $a) {
$parts = explode('/', $key);
$ref =& $data;
foreach ($parts as $p) $ref =& $ref[$p];
$ref_map[$key] =& $ref;
}
return filter_var_array($ref_map, $args);
}
var_dump(my_filter_array($data, $args));
Now the only question is how you deal with the mismatch between the validation record and the original data set. This I cannot answer without knowing how you need to use them.