I stumbled on a script that generates random names from two different types of words in an array. Code is following:
protected static $techTerms = array('AddOn', 'Algorithm', 'Architect', 'Array', 'Asynchronous', 'Avatar', 'Band', 'Base', 'Beta', 'Binary');
protected static $culinaryTerms = array('Appetit', 'Bake', 'Beurre', 'Bistro', 'Blend', 'Boil', 'Bouchees', 'Brew', 'Buffet', 'Caffe', 'Caffeine', 'Cake');
protected static $companyNameFormats = array(
'{{techTerm}}{{culinaryTerm}}',
'{{techTerm}}{{techTerm}}',
'{{culinaryTerm}}{{techTerm}}'
);
public static function techTerm()
{
return static::randomElement(static::$techTerms);
}
public static function culinaryTerm()
{
return static::randomElement(static::$culinaryTerms);
}
public function companyName()
{
$format = static::randomElement(static::$companyNameFormats);
return $this->generator->parse($format);
}
Basically, the script should create and return a random combination of words as defined in $companyNameFormats. This script requires Faker\Factory, but I'd like to make it independent. At this point, there are 2 problems:
randomElement as an undefined method, and generator->parse as Call to a member function parse() on null
I've managed to modify the script and make it work, but I am interested in how can I use the {{}} as given in $companyNameFormats and return the result without using an external library?
The modified script is as follows:
protected static function companyNameFormats()
{
$techArray = [];
$techArray[] = self::techTerm();
$culinaryArray = [];
$culinaryArray[] = self::culinaryTerm();
$result = array(
array_merge($techArray, $culinaryArray),
array_merge($techArray, $culinaryArray),
array_merge($culinaryArray, $techArray),
array_merge($techArray, $culinaryArray),
array_merge($culinaryArray, $techArray)
);
return $result;
}
public static function techTerm()
{
$techTermKey = array_rand(static::$techTerms, 1);
$techTermValue = static::$techTerms[$techTermKey];
return $techTermValue;
}
public static function culinaryTerm()
{
$culinaryTermsKey = array_rand(static::$culinaryTerms, 1);
$culinaryTermsValue = static::$culinaryTerms[$culinaryTermsKey];
return $culinaryTermsValue;
}
public function companyName()
{
$companyNameKey = array_rand(static::companyNameFormats(), 1);
$companyNameValue = static::companyNameFormats()[$companyNameKey];
return $companyNameValue;
}
They're probably doing something like preg_replace.
Quick and dirty example:
class Foo {
protected static array $foods = ["Pie", "Cake", "Yoghurt"];
protected static array $animals = ["Dog", "Cat", "Giraffe"];
protected static array $formats = [
"{{food}} {{animal}}",
"{{animal}} {{food}}"
];
public function get():string{
$format = $this->getRandomElement(self::$formats);
$format = preg_replace(
"/{{animal}}/",
$this->getRandomElement(self::$animals),
$format
);
return preg_replace(
"/{{food}}/",
$this->getRandomElement(self::$foods),
$format
);
}
protected function getRandomElement(array $elements):string{
return $elements[random_int(0, count($elements) - 1)];
}
}
echo (new Foo())->get(); // Cat Yoghurt
Based on the #Kyrre code, this is the final working example:
protected static $techTerms = array('AddOn', 'Algorithm', 'Architect', 'Array', 'Asynchronous', 'Avatar', 'Band', 'Base', 'Beta', 'Binary');
protected static $culinaryTerms = array('Appetit', 'Bake', 'Beurre', 'Bistro', 'Blend', 'Boil', 'Bouchees', 'Brew', 'Buffet', 'Caffe', 'Caffeine', 'Cake');
protected static $companyNameFormats = array(
'{{techTerm}} {{culinaryTerm}}',
'{{techTerm}} {{techTerm}}',
'{{culinaryTerm}} {{techTerm}}'
);
public static function techTerm()
{
return static::getRandomElement(static::$techTerms);
}
public static function culinaryTerm()
{
return static::getRandomElement(static::$culinaryTerms);
}
protected static function getRandomElement(array $elements): string
{
return $elements[random_int(0, count($elements) - 1)];
}
public function get(): string
{
$format = $this->getRandomElement(self::$companyNameFormats);
$format = preg_replace(
"/{{techTerm}}/",
$this->getRandomElement(self::$techTerms),
$format
);
return preg_replace(
"/{{culinaryTerm}}/",
$this->getRandomElement(self::$culinaryTerms),
$format
);
}
I created a standart class Loadercontent(controller) in Codeigniter.
Also in the same file a add abstract Search class and child class SearchDoctor:
When I try to get CI instance &get_instance(); at abstract constructor, I get NULL:
$this->_ci =&get_instance();
var_dump($this->_ci); // NULL
So after I can not use:
$this->_ci->load->view($this->view, $this->item);
because $this->_ci is empty. What is wrong in my code ot abstract class in CI? Also maybe you can ask something about code? Is it wrong?
The full code:
<?php
abstract class Search
{
protected $fields = array('country' => 'country', 'city' => 'city');
protected $table;
protected $limit = 20;
protected $offset = 0;
protected $items;
protected $rand = false;
protected $data;
protected $view;
protected $_ci;
public function __construct($input)
{
$this->_ci =&get_instance();
$this->data = $input;
$this->getPostGet();
}
public function getPostGet(){
if(empty($this->data)){
foreach($this->data as $key => $val){
$this->_check($val, $key);
}
}
}
public function _check($val, $key){
if(in_array($val, $this->fields)){
$this->items[] = $this->getField($val, $key);
}
}
public function getField($value, $key){
return $key. ' = '.$value;
}
public function doQuery(){
if(!empty($this->items)){
$limit = $this->formatLimit();
$this->items = $this->other_model->getItemsTable($this->query, $this->table, $limit);
}
}
public function formatLimit(){
$this->offset = (isset($this->data['limit'])) ? $this->data['limit'] : $this->offset;
$this->limit = (isset($this->data['limit'])) ? $this->offset + $this->limit : $this->limit;
return array('offset' => $this->limit, 'limit' => $this->limit);
}
public function addFields($array){
$this->fields = array_merge($this->fields, $array);
}
public function getView(){
$this->_ci->load->view($this->view, $this->item);
}
public function response(){
echo json_encode($this->view); die();
}
}
class SearchDoctor extends Search
{
protected $fields = array('name' => 'DetailToUsersName');
public function __construct($type)
{
$this->table = 'users';
$this->view = 'users/doctors_list';
$this->limit = 10;
$this->rand = true;
$this->addFields($this->fields);
parent::__construct($type);
}
}
/* Init class */
class Loadercontent {
public function index(){
if(isset($_GET) || isset($_POST)){
$class = 'Search';
if(isset($_POST['type'])){
$type = $_POST['type'];
$input = $_POST;
}
if(isset($_GET['type'])){
$type = $_GET['type'];
$input = $_GET;
}
$class = $class.$type;
if (class_exists($class)) {
$obj = new $class($input);
$obj->getView();
$obj->response();
}
}
}
}
?>
I am trying to remove irrelevant data from a multidimensional array.
The array is looking like this:
[6] => Array
(
[710C27E0-822A-4513-9D44-D97E929484A9] => Array
(
[documents] => Array
(
[0] => error message
)
)
)
And i am using the following code:
<?php
class report {
private static $instance;
private $data = array();
private function __construct() { }
private function __clone() { }
public function __destruct() { }
public static function singleton() {
if (!isset(self::$instance))
self::$instance = new self();
return self::$instance;
}
public function check() {
foreach($this->data as $key => &$values) {
foreach($values as $k => &$value) {
/* some checks */
if($return != null)
$values[$return] = $values[$k];
unset($values[$k]);
}
if(sizeof($values) == 0)
unset($this->data[$key];
}
}
public function __toString() {
print_r($this->data);
return '';
}
}
When i replace upper check function by the following code it is working, but i am looking for some better/cleaner and especially faster solution.
public function check() {
$_data = json_encode($this->data);
$data = json_decode($_data);
foreach($data as $key => &$values) {
foreach($values as $k => &$value) {
/* some checks */
if($return != null)
$values->$return = $values->$k;
unset($values->$k);
}
}
$this->data = $data;
}
SOLVED but not understanding it..
public function log($id, $guid, $job, $message) {
$this->data[$id][$guid][$job][] = $message;
}
when i var_dump($guid) it returns:
string(36) "710C27E0-822A-4513-9D44-D97E929484A9"
now i did a string cast:
var_dump((string)$guid);
returning:
string(36) "710C27E0-822A-4513-9D44-D97E929484A9"
but
$this->data[$id][(string)$guid][$job][] = $message;
works!
How can I call methods from an array of objects (that hold an array of objects). I read: Get array with results of object method on each item in an array of objects in PHP but could not get it.
Here is my testcode: the first object holds attributes, then an object holds a record of the multiple attributes.
/*--------------------------------- */
class SqliteAttribute {
private $_fieldname = '';
private $_fieldvalue = '';
private $_type = 'TEXT';
private $_key = true;
function __construct($fieldname, $fieldvalue, $text, $key) {
$this->_fieldname = $fieldname;
$this->_fieldvalue = $fieldvalue;
$this->_text = $text;
$this->_key = $key;
}
function AsArray() {
$tempArray = array('fieldname' => $this->_fieldname,
'fieldvalue' => $this->_fieldvalue,
'type' => $this->_type,
'key' => $this->_key
);
return $tempArray;
}
}
/*--------------------------------- */
class SqliteRecord {
private $_attributes = array();
function __construct() {
}
function AddAttribute($fieldname, $fieldvalue, $text, $key) {
$attribute = new SqliteAttribute($fieldname, $fieldvalue, $text, $key);
$this->attributes[] = $attribute;
var_dump($this->_attributes); // shows it!
}
function AsArray() {
$temp_array = array();
var_dump($this->_attributes); // shows nothing
foreach ($this->_attributes as $key => $value) {
$temp_array[] = $value->AsArray();
}
return $temp_array;
}
}
And I call it like this
function updateFiles($files, $rootpath) {
$recordset = new SqliteRecordSet;
foreach ($files as $file) {
$record = new SqliteRecord;
$record->AddAttribute('Path', $file[0], 'TEXT', true);
print_r($record->AsArray()); // shows nothing
}
$recordset->insertIfNotExist_index();
}
$this->attributes vs $this->_attributes
you should always develop code with error reporting set to E_ALL and display_errors on. php would have notified you of your mistake here.
Need load parameters to function, creating a variable name on the fly terrible thing, but I do not see another solution. This code contains an error please help
<?php
class A{
public $vars;
public $tab_names;
public $tab_names = array('car'=>'audi', 'honda' => 'name');
public $tab_fruits = array('name'=>'banana', 'banana'=>'fruit');
public function load($varr){
$$varr;
$this->vars = $varr;
}
public function display(){
return $this->vars;
}
}
$ob = new A;
$ob->load('tab_names');
$ob->display();
?>
Like this?
public function load($varr){
$this->vars = $this->$varr;
}
You should create separate methods to return the disparate types of data. They can be wrappers for the "real" function, if necessary:
public function displayCars() {
return $this->tab_names;
}
public function displayFruit() {
return $this->tab_fruits;
}
This will obviate the need for variable variables.
I don't think you can set the value of an variable at the start
public $tab_names = array('car'=>'audi', 'honda' => 'name');
public $tab_fruits = array('name'=>'banana', 'banana'=>'fruit');
which should be
public $tab_names;
public $tab_fruits;
then
class A {
public $vars;
public $variables;
public $tab_names;
public $tab_fruits;
public function __construct($variables){
$this->variables = $variables;
}
public function load($varr){
$this->vars = $this->variables[$varr];
}
public function display(){
return $this->vars;
}
}
$variables = array();
$variables['tab_names'] = array('car'=>'audi', 'honda' => 'name');
$variables['tab_fruits'] = array('name'=>'banana', 'banana'=>'fruit');
$ob = new A($variables);
$ob->load('tab_names');
print_r($ob->display());
This is how I would do it:
class A {
public $loaded_vars;
public static $vars = array(
'tab_names' => array('car'=>'audi', 'honda' => 'name'),
'tab_fruits' => array('name'=>'banana', 'banana'=>'fruit')
);
public function load( $name ){
$this->loaded_vars = self::$vars[ $name ];
}
public function display() {
return $this->loaded_vars;
}
}
$ob = new A;
$ob->load( 'tab_names' );
$ob->display();