I want to create a .INI file based on the values I get from database.
This are the values in my database for :
Now in the field parameter filed is the value i want to write in file each in new line.
I fetch the values like this:
$this->data['params'] = $this->parameter_m->get();
So I get all the values from the table.
I want to write values in file like this:
[INIDetails]
SipUserName=
Password=
Domain=
Proxy=
Port=
SipAuthName=
DisplayName=
ServerMode=
UCServer=
UCUserName=
UCPassword=
[DialPlan]
DP_Exception=
DP_Rule1=
DP_Rule2=
[Advanced]
OperationMode=
MutePkey=
Codec=
PTime=
AudioMode=
SoftwareAEC=
EchoTailLength=
PlaybackBuffer=
CaptureBuffer=
JBPrefetchDelay=
JBMaxDelay=
SipToS=
RTPToS=
LogLevel=
I have WRITE Function that writes into file
function write($file = NULL, $file_content = array(), $sections = TRUE) {
$this->file_content = (!empty($file_content)) ? $file_content : $this->file_content;
$this->file = ($file) ? $file : $this->file;
$this->sections = $sections;
$content = NULL;
if ($this->sections) {
foreach ($this->file_content as $section => $file_content) {
$content .= '[' . $section . ']' . PHP_EOL;
foreach ($file_content as $key => $val) {
if (is_array($val)) {
foreach ($val as $v) {
$content .= $key . '[]=' . (is_numeric($v) ? $v : $v ) . PHP_EOL;
}
} elseif (empty($val)) {
$content .= $key . '=' . PHP_EOL;
} else {
$content .= $key . '=' . (is_numeric($val) ? $val : $val ) . PHP_EOL;
}
}
$content .= PHP_EOL;
}
} else {
foreach ($this->file_content as $key => $val) {
if (is_array($val)) {
foreach ($val as $v) {
$content .= $key . '[] = ' . (is_numeric($v) ? $v : '"' . $v . '"') . PHP_EOL;
}
} elseif (empty($val)) {
$content .= $key . ' = ' . PHP_EOL;
} else {
$content .= $key . ' = ' . (is_numeric($val) ? $val : '"' . $val . '"') . PHP_EOL;
}
}
}
return (($handle = fopen($this->file, 'w+')) && fwrite($handle, trim($content)) && fclose($handle)) ? TRUE : FALSE;
}
And i use that function like this :
$path = "./uploads/";
$filename = "default.ini";
$this->load->helper('file');
$file = $path.$filename;
$this->load->library('ini');
$ini = new INI($file);
$ini->write($file, $this->data['params']);
So i how to write the array of values i get from database into file ?
As you can see there is a filed called Parameter_Type i want to set it as section in INI file.
I'm guessing that your parameter_m is your model which have get() function where it returns array values from your table. What I think, the problem is that your model return incorrect structure of your array. Your array should have structure like:
array(
"parameter_type" => array(
"parameter" => value
)
)
in your model's get function, there should be something like:
class parameter_m extends CI_Model {
public function get()
{
$query = $this->db->get('your_parameter_table');
$assoc_arr = array();
foreach ($query->result() as $row)
{
$assoc_arr[$row->parameter_type][$row->parameter] = '';
}
return $assoc_arr;
}
}
Using the get() it should output:
array(
"INIDetails" => array(
"SipUserName" => '',
"Password" => '',
"Domain" => '',
"Proxy" => '',
"Port" => '',
"SipAuthName" => '',
"DisplayName" => '',
"ServerMode" => '',
"UCServer" => '',
"UCUserName" => '',
"UCPassword" => ''
),
"DialPlan" => array(
"DP_Exception" => '',
"DP_Rule1" => '',
"DP_Rule2" => ''
),
"Advanced" => array(
"OperationMode" => '',
"MutePkey" => '',
"Codec" => '',
"PTime" => '',
"AudioMode" => '',
"SoftwareAEC" => '',
"EchoTailLength" => '',
"PlaybackBuffer" => '',
"CaptureBuffer" => '',
"JBPrefetchDelay" => '',
"JBMaxDelay" => '',
"SipToS" => '',
"RTPToS" => '',
"LogLevel" => ''
)
);
Related
I have a PHP tree structure (array max depth: 5):
$arr = array(
'31' => array(
'Amsterdam' => array(),
'Rotterdam' => array(),
'Den Haag' => array(),
'Utrecht' => array(),
'Eindhoven' => array(),
'Tilburg' => array(),
'Almere' => array(
'036' => array(
'BU00340212' => array(
'name' => 'Muziekwijk Noord',
'residents' => array(
'Henk',
'Dirk',
'Jaap',
),
),
'BU00340213' => array(
'name' => 'Muziekwijk Zuid',
'residents' => array(
'Wim',
'Pim',
'Jim',
'Tim',
),
),
)
),
'Groningen' => array(),
'Breda' => array(),
'Nijmegen' => array(),
)
);
I would like to have this output:
Almere(netnummer: 036)(cbscode: BU00340212): Henk
Almere(netnummer: 036)(cbscode: BU00340212): Dirk
Almere(netnummer: 036)(cbscode: BU00340212): Jaap
Almere(netnummer: 036)(cbscode: BU00340213): Wim
Almere(netnummer: 036)(cbscode: BU00340213): Pim
Almere(netnummer: 036)(cbscode: BU00340213): Jim
Almere(netnummer: 036)(cbscode: BU00340213): Tim
So I did some coding by myself. The code below produces the output that I want.
foreach($arr as $unitKey => $citySet){
foreach($citySet as $cityName => $cityData){
if($cityName === 'Almere'){
$almere = $citySet[$cityName];
foreach($almere as $netnummer => $netData){
foreach($netData as $cbsCode => $data){
foreach($data['residents'] as $residents){
echo $cityName . '(netnummer: '. $netnummer .')(cbscode: '. $cbsCode .'): ' . $residents . '<br>';
}
}
}
}
}
}
The code displayed above makes use of 5 foreaches, and I'm doubting if that's a good idea. So I tried to reduce a couple foreaches like this:
$arrB = $arr['31']['Almere']['036'];
foreach($arrB as $k => $netData){
foreach($netData as $field => $fieldData){
if($field === 'residents') {
foreach($fieldData as $resident){
echo 'Almere(netnummer: 036)(cbscode: '. $k .'): ' . $resident . '<br>';
}
}
}
}
The code displayed above makes use of 3 foreaches. That is because it doesn't traverse the full tree.
I want to traverse the full tree with 1 foreach, and produce the output I was aiming for. So I was thinking about RecursiveArray in combination with RecursiveIteratorIterator, but I can't get the cbscode if I use this approach. See for yourself:
$recursiveArrayIterator = new RecursiveArrayIterator($arr);
$recursiveIteratorIterator = new RecursiveIteratorIterator($recursiveArrayIterator);
foreach($recursiveIteratorIterator as $k => $v){
if($k !== 'name'){
echo 'Almere(netnummer: 036)(cbscode: ???): ' . $v . '<br>';
}
}
Q1: is this possible to traverse the tree structure with one foreach with the shown output?
Q2:if it is possible, can you show the code? if not, is it possible to reduce the amount of used foreaches to 2?
-- Edit --
Q (rephrased): What is most readable way to fully traverse an 5 level deep array?
You can short this down to:
$arrB = $arr['31']['Almere']['036'];
foreach($arrB as $code => $val) {
if (isset($val["residents"])) {
$prefix = 'Almere(netnummer: 036)(cbscode: '. $code .'): ';
echo $prefix . implode('<br>' . $prefix, $val["residents"]) . '<br>';
}
}
Live example: 3v4l
I invested some time in this problem, and came with a functional programming approach:
function recursive($data, $countryCode = null, $countryData = null, $city = null, $cityData = null, $netNummer = null, $netData = null, $cbscode = null, $cbsData = null, $residents = null){
if($residents){
$resident = array_shift($residents);
echo $city . '(netnummer: ' . $netNummer . ')(cbscode: ' . $cbscode .'): ' . $resident . '<br>';
if($residents){
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData, $residents);
}
return null;
}
if($cbscode && $cbsData){
$residents = $cbsData['residents'];
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData, $residents);
}
if($countryCode && $countryData && $netData){
$cbscode = key($netData);
$cbsData = array_shift($netData);
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData);
}
if($countryCode && $countryData && $city && $cityData){
$netNummer = key($cityData);
$netData = array_shift($cityData);
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData);
}
if($countryCode && $countryData){
$city = key($countryData);
$cityData = array_shift($countryData);
recursive($data, $countryCode, $countryData, $city, $cityData);
}
if($data){
$countryCode = key($data);
$countryData = array_shift($data);
if($countryData){
recursive($data, $countryCode, $countryData);
}
}
return null;
}
recursive($arr);
Online source: https://3v4l.org/rsf5o
I'm only using a small part of this function actually but I wanted to post it all to provide the big picture. There is a part of the query in this function that finds recent attachments a user has posted to the forums. The block is on the user profile. IT works but the problem is ... it's VERY slow!! Core attachments locks up for 30+ seconds and makes my site unusable.
Any one who could help it would be much appreciated.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->limit = $limit;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
Hi i am using CakePHP version 2.x
I am print my array using
pr($this->request->params['named']);
//Output
Array
(
[street_name] => Bhubaneswar
[house_number] => 1247
[phone] => xxxxxxxx
[zip] => xxxxx
)
In above array i want to view looks like
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
How to convert above array in string format?
Try this:
$strResult = "";
foreach ($this->request->params['named'] as $key=>$value){
$strResult .= "/{$key}:{$value}";
}
The most easy and speedy solution.
$result = '';
foreach ($this->request->params['name'] as $k => $v) {
$result .= sprintf('/%s:%s', $k, $v);
}
As a one-liner:
echo '/' . str_replace('=', ':', http_build_query($array, '', '/'));
Would output:
/street_name:Bhubaneswar/house_number:1247/phone:xxx/zip:xxx
foreach (array_expression as $key => $value){
echo "/". $key . ":" . $value;
}
Try following code:
$ar = array('street_name' => 'Bhubaneswar',
'house_number' => 1247,
'phone' => 'xxxxxxxx',
'zip' => 'xxxxx');
echo convert($ar);
function convert($ar)
{
$str = '';
foreach($ar as $i=>$k)
{
$str .= '/'.$i.':'.$k;
}
return $str;
}
Output
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
function implode_with_keys($glue, $separator, $pieces)
{
$string = '';
foreach ($pieces as $key => $value) {
$string .= $glue . $key . $separator . $value;
}
return $string;
}
In your case you'd use it like this:
implode_with_keys('/', ':', $this->request->params['named']);
This will return the desired string /street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx.
<?php
$array = array(
'street_name' => 'Bhubaneswar',
'house_number' => '1247',
'phone' => 'xxxxxxxx',
'zip' => 'xxxxx',
);
while (current($array)) {
echo '/'.key($array).':'.$array[key($array)];
next($array);
}
?>
this will return
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
I have an array like
$a = array(
'aaa' => "sample",
'bbb' => "sample2",
'ccc' => "adas",
'ddd' => "2",
'eee' => '2013-09-05',
'fff' => "false",
'ggg' => "893",
'qqq' => '2013-09-05',
'sss' => array(
"iii" => array(
'vvv' => "sample3",
'xxx' => 500,
)
),
'nnn' => '2013-09-05',
'mmm' => "Normal",
);
and I want to convert it to xml but witout using SimpleXMLElement or another function. That's why I have tried to do it with foreach. Here is my code ;
$data = '';
foreach ($a as $k => $v) {
if (is_array($k)) {
$data .= "<a:$k>" . $v . "</a:$k>";
foreach ($k as $j => $m) {
if (is_array($j)) {
foreach ($j as $s => $p) {
$data .= "<a:$s>" . $p . "</a:$s>";
}
} else {
$data .= "<a:$j>" . $m . "</a:$j>";
}
}
} else {
$data .= "<a:$k>" . $v . "</a:$k>";
}
}
but it's not working. I can make it work with hashmaps in another language but it must be in php. How can I do this.
Thanks.
You could try this:
function createXml($array, $level = 0)
{
$xml = ($level == 0) ? '<?xml version="1.0" encoding="ISO-8859-1"?>'.PHP_EOL : '';
$tab = str_pad('', $level, ' ', STR_PAD_LEFT);
foreach($array as $node => $value)
{
$xml .= "{$tab}<{$node}>";
if(!is_array($value))
{
$xml .= $value;
}
else
{
$level++;
$xml .= PHP_EOL.createXml($value, $level).$tab;
}
$xml .= "</{$node}>".PHP_EOL;
}
return $xml;
}
$xml = createXml($a);
echo $xml;
I need to read nested arrays without knowing how the array will look.
For example;
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Needs to be formatted to strings like:
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/
But the array can be of any size with any number of nested arrays inside it.
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
function printArray($array)
{
foreach ($array as $key=>$value)
{
echo $key.'/';
if (is_array($value))
{
printArray($value);
} else {
echo '<br>';
}
}
}
printArray($data);
If you want to output only the name of array elements then this recursive function will do the trick.
Your data:
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Function:
function array2str($array, $str) {
foreach($array as $key => $val) {
if (is_array($val) ) {
$str .= $key . '/';
array2str($val, $str);
}
}
echo $str.'<br />';
return $str;
}
array2str($data);
As you can see the script does ECHO in itself with <br /> to break the line when viewing results in a browser.
One way would to walk recursively through array with function similar to this:
<?php
function f($d, $str = '') {
foreach ($d as $key => $val) {
if (is_array($val)) f($val, $str . '/' . $key); // If this element is array parse next level
else print_r($str . '/' . $key . '/'); // Output current string or do what you need to do with it..
}
}
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
f($data);
with that function:
<?php
function print_tree ($data, $prefix = '', &$index = 1) {
foreach($data as $key => $datum) {
echo $index++ . '. ' . ($new_prefix = $prefix . $key . '/') . PHP_EOL;
if (is_array($datum)) {
print_tree ($datum, $new_prefix, $index);
}
}
}
I get
Data1_lvl1/
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/