PHP - Adding multiple database entries - php

I have a function that adds an entry to the database, the code i have at the moment is as follows:
function create_internal_role($rolename, $rolekey)
{
$data = array(
'name' => $rolename,
'key' => $rolekey.'1'
);
if (!is_null($res = $this->ci->internal_roles->create_role($data))) {
return $data;
}
return NULL;
}
What i want to do, is using the same function add another 2 data arrays with a 2 and 3 behind the $rolekey, so that with the one function, it adds 3 lots of data, rolekey1, rolekey2 and rolekey3
How would i go about doing that?

With out knowing about your structure and from the current phrasing of your question, the obvious answer would seem to be this:
function create_internal_role($rolename, $rolekey)
{
$ret = array();
$data = array(
'name' => $rolename,
'key' => $rolekey.'1'
);
if (!is_null($res = $this->ci->internal_roles->create_role($data))) {
$ret[] = $data;
}
$data = array(
'name' => $rolename,
'key' => $rolekey.'2'
);
if (!is_null($res = $this->ci->internal_roles->create_role($data))) {
$ret[] = $data;
}
$data = array(
'name' => $rolename,
'key' => $rolekey.'3'
);
if (!is_null($res = $this->ci->internal_roles->create_role($data))) {
$ret[] = $data;
}
return $ret;
}
If you give more detail in your question, I may be able to give you a better answer.

Perhaps something like this will work:
function create_internal_role($rolename, $rolekey)
{
// define role key indecies
$indexArray = array(1,2,3);
$ret = array(); // return array
// create roles
for(i=0; i<count($indexArray); $i++){
$data = array(
'name' => $rolename,
'key' => $rolekey.indexArray[$i]
);
if (!is_null($res = $this->ci->internal_roles->create_role($data))) {
$ret[] = $data;
}else{
$ret[] = null;
}
}
return $ret;
}

Related

recursion function on tree data to get path

I want to write function which receive me path to top element, but I can't figure out how it should work..
My example data:
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getParents(8678678); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
// and my recursion function I tried.
function getObjectPath($object_id) {
if ($object_id == null) {
return [];
}
$parents = getObjectParents($object_id);
foreach ($parents as $parent) {
return array($object_id => getObjectPath($parent->nid));
}
}
It doesn't work way I need, on the return in getObjectPath(8678678) I'd like to have return array like that:
array(
3546456 => array(
12312312 => array(
8678678
)
),
567978 => array(
8678678
)
);
I think you almost got it, need to have some other check before returning
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getObjectPath(8678678, $data); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
echo "<pre>";
print_r($parents);
// and my recursion function I tried.
function getParents($object_id, $data) {
$return = [];
foreach($data as $key => $value) {
if(in_array($object_id, $value)) {
$return[] = $key;
}
}
return $return;
}
// and my recursion function I tried.
function getObjectPath($object_id, $data) {
$return = [];
$parents = getParents($object_id, $data);
foreach($parents as $parent) {
$temp = getObjectPath($parent, $data);
if(!empty($temp)) {
$return[key($temp)][$parent] = $object_id;
} else {
$return[$parent] = $object_id;
}
}
return $return;
}

Why is my variable data getting dropped after the first foreach loop?

I am using CodeIgniter to insert records in my database. Everything is working perfectly, except I can't seem to understand why the value of a nested array is losing its value after the first foreach loop.
php
// $data is all data (array) passed from controller method.
public function create($data)
{
$my_data = array(
'name' => $data['name'],
....
);
if ($this->db->insert('myTable', $my_data)) {
$insert_id = $this->db->insert_id();
// $data['mySecondCheckbox'] has value here
foreach ($first_data['myFirstCheckbox'] as $cb1) {
$first_data = array(
'fk_foo_id' => $insert_id,
'fk_cb_id' => $cb1
);
$this->db->insert('mySecondTable', $first_data);
}
// $data['mySecondCheckbox'] has no value here
foreach ($data['mySecondCheckbox'] as $cb2) {
$second_data = array(
'fk_foo_id' => $insert_id,
'fk_cb_id' => $cb2
);
$this->db->insert('myThirdTable', $second_data);
}
return $insert_id;
} else {
return false;
}
}
SOLUTION
Thank you #John! Pretty obvious after sleeping on it. At the time, I was thinking that $data was specific to within each of the each scope.
php
// $data is all data (array) passed from controller method.
public function create($data)
{
$my_data = array(
'name' => $data['name'],
....
);
if ($this->db->insert('myTable', $my_data)) {
$insert_id = $this->db->insert_id();
// $data['mySecondCheckbox'] has value here
foreach ($data['myFirstCheckbox'] as $cb1) {
$first_data = array(
'fk_foo_id' => $insert_id,
'fk_cb_id' => $cb1
);
$this->db->insert('mySecondTable', $first_data);
}
// $data['mySecondCheckbox'] has no value here
foreach ($second_data['mySecondCheckbox'] as $cb2) {
$data = array(
'fk_foo_id' => $insert_id,
'fk_cb_id' => $cb2
);
$this->db->insert('myThirdTable', $second_data);
}
return $insert_id;
} else {
return false;
}
}
The first line in your foreach loop is resetting the subject in your loop "$data". Rename the variable and you should be good

PHP - Arrays and Foreach

I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}

Convert multidimensional array to nested set array

im having a little problem i need some help with.
Im trying to convert a multidimensional array into a flatten array with nested set values right and left like so:
$array = {
'id' => 1
'name' => 'john'
'childs' => array(
array(
'id' => 1
'name' => 'jane'
)
)
}
to
$array = {
array(
'id' => 1,
'name' => 'john'
'left' => '1'
'right' => '4'
),
array(
'id' => 1,
'name' => 'jane'
'left' => '2'
'right' => '3'
)
}
Any help is appreciated!
I asked a very similar question and got a result, so thought I'd send it on for you. I realise this is quite an old topic, but still worth getting an answer. I've included my data, but would be easily adapted for yours.
$JSON = '[{"id":1,"children":[{"id":2,"children":[{"id":3},{"id":4}]},{"id":5}]}]';
$cleanJSON = json_decode($JSON,true);
$a_newTree = array();
function recurseTree($structure,$previousLeft)
{
global $a_newTree; // Get global Variable to store results in.
$indexed = array(); // Bucket of results.
$indexed['id'] = $structure['id']; // Set ID
$indexed['left'] = $previousLeft + 1; // Set Left
$lastRight = $indexed['left'];
$i_count = 0;
if ($structure['children'])
{
foreach ($structure['children'] as $a_child)
{
$lastRight = recurseTree($structure['children'][$i_count],$lastRight);
$i_count++;
}
}
$indexed['right'] = $lastRight + 1; // Set Right
array_push($a_newTree,$indexed); // Push onto stack
return $indexed['right'];
}
recurseTree($cleanJSON[0],0);
print_r($a_newTree);
function restructRecursive($array, $left = 1) {
if (isset($array['childs'])) {
$result = array();
foreach ($array['childs'] as $child) {
$result = array_merge($result, restructRecursive($child, $left+1));
}
unset($array['childs']);
}
$array['left'] = $left;
return array_merge(array($array), $result);
}
$newStruct = restructRecursive($oldStruct);
For anyone coming here and looking for a solution, loneTraceur's solution works fine. However, I needed one in OOP, so here is my version of it.
<?php
class NestedSet
{
protected $tree = [];
public function deconstruct($tree, $left = 0)
{
$this->flattenTree($tree, $left);
return $this->tree;
}
protected function flattenTree($tree, $left)
{
$indexed = [];
$indexed['id'] = $tree['id'];
$indexed['_lft'] = $left + 1;
$right = $indexed['_lft'];
if (isset($tree['children']) && count($tree['children'])) {
foreach ($tree['children'] as $child) {
$right = $this->flattenTree($child, $right);
}
}
$indexed['_rgt'] = $right + 1;
$this->tree[] = $indexed;
return $indexed['_rgt'];
}
}
You would run it like this:
$NestedSet = new NestedSet;
$flat = $NestedSet->deconstruct($tree):
This code is based on the other answer.

Getting Nested Values From Associative Array

This is sort of a general implementation question. If I have an arbitrarily deep array, and I do not know before hand what the keys will be, what is the best way to access the values at specific paths of the associative array? For example, given the array:
array(
'great-grandparent' = array(
'grandparent' = array(
'parent' = array(
'child' = 'value';
),
'parent2' = 'value';
),
'grandparent2' = 'value';
)
);
Whats the best way to access the value at $array['great-grandparent']['grandparent']['parent']['child'] keeping in mind that I don't know the keys beforehand. I have used eval to construct the above syntax as a string with variable names and then eval'd the string to get the data. But eval is slow and I was hoping for something faster. Something like $class->getConfigValue('great-grandparent/grandparent/'.$parent.'/child'); that would return 'value'
Example of Eval Code
public function getValue($path, $withAttributes=false) {
$path = explode('/', $path);
$rs = '$r = $this->_data[\'config\']';
foreach ($path as $attr) {
$rs .= '[\'' . $attr . '\']';
}
$rs .= ';';
$r = null;
#eval($rs);
if($withAttributes === false) {
$r = $this->_removeAttributes($r);
}
return $r;
}
I don't know about the potential speed but you don't need to use eval to do a search like that :
$conf = array(
'great-grandparent' => array(
'grandparent' => array(
'parent' => array(
'child' => 'value searched'
),
'parent2' => 'value'
),
'grandparent2' => 'value'
)
);
$path = 'great-grandparent/grandparent/parent/child';
$path = explode('/', $path);
$result = $conf;
while(count($path) > 0) {
$part = array_shift($path);
if (is_array($result) && array_key_exists($part, $result)) {
$result = $result[$part];
} else {
$result = null;
break;
}
}
echo $result;
Here we go, my solution:
$tree = array(
'great-grandparent' => array(
'grandparent' => array(
'parent' => array(
'child' => 'value1'
),
'parent2' => 'value2'
),
'grandparent2' => 'value3'
)
);
$pathParts = explode('/','great-grandparent/grandparent/parent/child');
$pathParts = array_reverse($pathParts);
echo retrieveValueForPath($tree, $pathParts);
function retrieveValueForPath($node, $pathParts) {
foreach($node as $key => $value) {
if(($key == $pathParts[count($pathParts)-1]) && (count($pathParts)==1)) {
return $value;
}
if($key == $pathParts[count($pathParts)-1]) {
array_pop($pathParts);
}
if(is_array($value)) {
$result = retrieveValueForPath($value, $pathParts);
}
}
return $result;
}

Categories