Populating database field with multiple value - php

I am working on populating the database tables. The table have fields which some of them are enum.
Consider a user which have a field status , whose values can be active, inactive etc. Assume we can modify the configuration values and running the script the data can be populated accordingly.
Let us represent the user table whose status field as
'status' => array(
'active' => 3,
'inactive',
'deleted',
),
In this case assume we need to create 3 users with status , active. 1 user with status inactive and 1 with deleted.
The table may be having more enum fields. So the config can expand. Depending on the configuration and fields the values will be multiples.
Consider the below example.
Eg :
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
In this case there need to populate table1 whose field field1 with active, inactive, deleted and roles with admin, user, editor etc. ( The active, inactive etc are provided just for example. It can be just values. )
The idea is to generate more users depending on the count if any provided.
Eg :
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
)
....,
'more-fields' => array(
'more-values',
)
So that there will be
10 * 4 => active users (10 * 2 active admin / 10 active user, 10 active editor ) +
2 * 4 => inactive users ( 2 inactive admin , 1 user, 1 editor ) +
3 * 4 => deleted users in total.
I am struggling to build the algorithm for the same.
array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
)
// In this example you can see we have not covered the fields of the table when they are more than 1 on save.It looks we need to build the array with values first.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
} else {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
}
}
}
}
}
UPDATE :
Changes made according to #the-fourth-bird answer https://stackoverflow.com/a/33354032/487878
Problem is it only look for 2 fields, the fields can be 1 or n.

Are you looking for a setup like this? (Not sure what the fields for the User can be, I used 'role' and 'admin' in this example.)
$fields = array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin',
'user',
'editor'
)
);
$roles = $fields['roles'];
$statuses = $fields['status'];
foreach ($roles as $role) {
foreach ($statuses as $status => $statusCount) {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->role = $role;
$model->status = $status;
}
}
}
// Update with dynamic properties
<?php
class table1name {
public function save() {}
}
class table2name {
public function save() {}
}
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user' => 2,
'editor'
),
'more-fields' => array(
'more-values' => 2,
),
'color' => array(
'blue' => 2,
'red'
),
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
// Adjust data structure
// If the key is a string, turn the key into values for the given multiplier in the same array.
// Then unset the key.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
for ($i = 0; $i< $statusCount; $i++) {
$config[$table][$field][] = $key;
}
unset($config[$table][$field][(string)$key]);
}
}
}
}
$cartesians = [];
// If you want all the possible combinations for for example the 'table1name', you need a cartesian product. Used the function from this page:
//http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays
function cartesian($input) {
$input = array_filter($input);
$result = array(array());
foreach ($input as $key => $values) {
$append = array();
foreach($result as $product) {
foreach($values as $item) {
$product[$key] = $item;
$append[] = $product;
}
}
$result = $append;
}
return $result;
}
// Create the cartesian products for all the keys in the $config array.
foreach ($config as $key => $tables) {
$cartesians[$key] = cartesian($tables);
}
// Loop all the objects created by the cartesian function.
foreach ($cartesians as $objectName => $cartesian) {
foreach($cartesian as $key => $value) {
$model = new $objectName();
$model->$key = $value;
$model->save();
}
}

Related

Call each value from array of an object

I have function in class, which returns array with 4 3-4 rows. I have to use each value from related row in table values. I can print builded function atrray, and can print on parent file, but can not get values for elements for each row. Here is my class file:
<?php
class Anyclass
{
public function $monthly($array)
{
.
.
.
}
public function myfunction($array)
{
foreach ($ShowMonths as $duration) {
$array['Credit']['downpayment'] = 0;
$array['Credit']['duration'] = $duration;
$monthly = $this->monthly($array);
$Table['Options'][] = array(
'downpayment' => $array['Credit']['downpayment'],
'duration' => $array['Credit']['duration'],
'monthly' => $monthly,
'total' => $monthly * $array['Credit']['duration'] + $array['Credit']['downpayment']
);
}
print_r($Table);
}
}
Here is my main file
include_once('mypathtofile/FileWithClass.php');
$Cll = new NewOne();
$array = array(
'Rule' => array(
'rule_id' => 1,
'rule_name' => 'Mobile phones',
'interest' => 0.01,
'comission' => 0.01,
'best_offer_downpayment' => 0.5,
'best_offer_duration' => 6
),
'Product' => array(
'product_id' => 1,
'category_id' => 1,
'manufacturer_id' => 1,
'product_price' => 500
),
'Credit' => array(
'downpayment' => 100,
'duration' => 6
)
);
$prtst = $Cll->myfunction($array);
How can I call each elemet for each row?
I'm not sure what you are trying to do, but if you need to get each value in a multidimensional array - you can use recursion:
function get_value($array){
foreach($array as $item){
if(is_array($item)){
get_value($item);
} else {
echo $item;
}
}
}

rename Model Name from find('all') with cakePHP 2.X

I have a Model Order.
When I do find('all') in my table Order, cakephp return data like this:
array(
(int) 0 => array(
'Order' => array(
'id' => '10'
)
),
(int) 1 => array(
'Order' => array(
'id' => '11'
)
)
)
Is there any way for rename 'Order' into 'myTEST' ?
In your Order model you could possibly implement an afterFind callback to replace [Order] with [myTEST]. Something like this might work for you:
public function afterFind($results, $primary = false) {
$new_results = array();
foreach ($results as $key => $val) {
foreach($val as $v){
$new_results[$key]['myTEST'] = $v;
}
}
return $new_results;
// OR you could also take this approach - Less coding and perhaps more efficient
// foreach ($results as $key => $val){
// $results[$key]['myTEST'] = $results[$key]['Order'];
// unset($results[$key]['Order']);
// }
// return $results;
}
I have not tested this at all.

How to extract the relevant elements from this array of associative arrays?

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

How retrieve specific duplicate array values with PHP

$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);

Array - custom foreach function

I have an array in this form:
$data = array(
array(
'id' => '1',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'bar',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'different,
'bar' => 'bar',
'page' => 'back',
),
array(
'id' => 'another',
'title' => __("Custom CSS",'solidstyle_admin'),
'foo' => 'bar',
'page' => 'back',
),
);
And I want to list all ids grouped by pages and saved as variables, so if the above array is an input then output will look just like this one:
$front = array('1','bar');
$back = array('different','another');
//$data['page'] = array($id1, $id2, (...));
I was trying to do that using foreach and this is how it starts:
function my_output() {
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
}
return $output;
}
I was trying multiple foreach loops, and the best result I got was:
front = 1
front = bar
back = different
back = another
But I have absolutely no idea how to achieve what I want to do, I don't want anyone to do my job, just any hints? Keep in mind I'm a bit new to PHP and I don't know too much about arrays.
Thank you!
Sounds like you want:
$ids = array();
foreach ($data as $page) {
$pageName = $page['page'];
// create an empty array for your IDs
if (!isset($ids[$pageName])) {
$ids[$pageName] = array();
}
// add to the array of IDs
$ids[$pageName][] = $page['id'];
}
var_dump($ids); // array('front' => array('1', 'bar'), ...
Stick with the loop idea and do a conditional check.
function my_output() {
$front = array();
$back = array();
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
if ($page === 'front') {
$front[] = $id;
} else if ($page === 'back') {
$back[] = $id;
}
}
// Not sure what you want to return here, but you could return an array of pages
$output = array('front' => $front, 'back' => $back);
return $output;
}
This will return something similar to:
$output = array(
'front' => array(
0 => '1',
1 => 'bar',
),
'back' => array(
0 => 'something',
1 => 'another',
)
)
Edit: Keep in mind that my answer only accounts for the two pages you listed in your answer. If you have more pages you can also use what cbuckley's answer showed.

Categories