How to fill an array with another array? - php

I'm trying to create clones of an element in an object and set new names for the clones.
class My_Obj{
var $obj;
var $obj_name;
var clone; //----int input to say how many clones are needed
var clone_names;//----array input to make clone's name different from $obj
function __construct( $args = '' ) {
$defaults=array(
/* codes to set up the default $obj */
)
if ( $this->clone >0 ){
for ( $i = 0; $i <= $this->clone; ++$i ){
$clone_obj[$i]['name'] = /* need to loop through array $clone_name to fill this */
}
}
/* other codes */
}
The $clone_names, for example, can be array('cat', 'dog', 'bird'). It doesn't matter which order as long as each clone get a name. I would like to learn how to do this. Thanks!

If I understand your question correctly, you want to fill the array $clone_obj with values from $clone_names - up to the number of clones specified in $clone?
If that's the case, this may work (I've rewritten the sample class you used):
class My_Obj {
public $clone = 0; //----int input to say how many clones are needed
public $clone_names = array(); //----array input to make clone's name different from $obj
private $clone_obj = array(); // array to store cloned names in
function __construct($args = '') {
for ($i=0; $i<$this->clone; $i++) {
// copy the name in "$clone_names" to "$clone_obj", if it exists
$this->clone_obj[$i] = array();
$this->clone_obj[$i]['name'] = (isset($this->clone_names[$i]) ? $this->clone_names[$i] : '');
}
}
}

Related

How to create single array of id's from parent and child array

I'm Trying to create single array that contains all the ID of parent and child from the database.
But all I was getting is single data.
My ideal output is:
array('160', '161', '162', '163', '164');
what am I getting is only
array('160');
Here is what I've done so far.
public function arrayId(array $elements) {
$where_in = array();
foreach($elements as $element){
if($element->isArray) {
$elems = $this->my_model->select_where('tbl_policies', array('parent_id' => $element->id));
$this->arrayId($elems);
}
$where_in[] = $element->id;
}
return $where_in;
}
$id = 160; //for instance
$elements = $this->my_model->select_where('tbl_policies', array('id' => $id));
$where_in = $this->arrayId($elements);
die(print_r($where_in));
and the data I'm fetching here:
tbl_policies
It's kinda difficult for me to construct questions. So please if something is not clear, do comment below, I'll try my best to make it more understandable. Thanks in advance.
I understand, that you want to delete a parent with all its children and grandchildren. But you do it not directly and sequentially rather want to collect all ids of the records to be deleted. You should go following steps:
Parent-Id (example 160) is already known. Add this to your list.
Write a recursive function such as getChildrenIds(parentId).
Within this function you should iterate over children. And if a child has the flag "isArray" (according to your application logic) then you should call getChildrenIds(currentChildId)
I have written following function. It should work.
public function getChildrenIds( int $parentId, array &$idList) {
$idList[] = $parentId;
$records = $this->my_model->select_where('tbl_policies', array('parent_id' => $parentId));
foreach($records as $r){
if($r->isArray)
$this->getChildrenIds($r->id, $idList);
else
$idList[] = $r->id;
}
return;
}
public function CollectIds(){
$id = 160; //for instance
$where_in = array();
$this->getChildrenIds($id, $where_in);
}
Please notice, that $where_in passed by reference to the recursive function getChildrenIds() and filled there.

OctoberCMS - How to access properties of a component in a function inside of the php section?

Is it possible to access the properties of a component e.g. blogPosts in the OnStart() function? If so, how?
title = "Blog Category"
url = "/blog/category/:slug/:page?"
[blogPosts]
categoryFilter = ":slug"
postsPerPage = 3
==
function onStart()
{
// Access categoryFilter property
$catfilter = ???
...
}
==
I got to ask why do you need to access the component properties?
You can access the parameter ':slug' $this->param('slug');.
This should work for you to get the array of properties.
function onStart() {
$this['properties'] = collect($this->page->components['blogPosts'])->last()['postsPerPage'];
}
I am adding another way to get the properties from the array. I am assuming that properties is probably always last but if it isn't:
$array = collect($this->page->components['blogPosts'])->toArray();
$properties = [];
foreach ( $array as $key => $property) {
if ( strpos($key, 'properties') !== false ) {
$properties[$key] = $property;
}
}
$this['properties'] = $properties['postsPerPage'];

Array not initialized

I use a method in my class that returns an array of members:
public function getArrTranslatable()
{
//------------------------- DECLARE ---------------------------//
return array( $this->artDescription, //
$this->artKeywords, //
$this->artMaintenanceMsg, //
$this->artTitle );
}
In another class, i get that array then iterate on it to perform some actions, like instanciate array for each members:
$arrFieldToTranslate = $p_translatable->getArrTranslatable();
//------------------------- DECLARE ---------------------------//
foreach( $arrFieldToTranslate as $artField )
{
// Instanciate translatable array.
if( $artField == null )
{
$artField = array();
}
$artField[ $p_idLang ] = "";
}
The code seems to work fine, because i pass in the array instanciation, but when i get thoses members in my view, later, they're null.

PHPExcel - Using example read fiter

I'm just getting started with PHPExcel. My very large spreadsheets cannot be loaded whole into memory (memory fail). To only load the parts of the worksheet I need, I'm trying to use the MyReadFilter code that was provided in the documentation, but the code is a bit above me and I'm hoping someone can help me understand it.
From the PHPExcel documentation, here's the function:
class ReadFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
private $_columns = array();
/** Get the list of rows and columns to read */
public function __construct($startRow, $endRow, $columns) {
$this->_startRow = $startRow;
$this->_endRow = $endRow;
$this->_columns = $columns;
}
public function readCell($column, $row, $worksheetName = '') {
// Only read the rows and columns that were configured
if ($row >= $this->_startRow && $row <= $this->_endRow) {
if (in_array($column,$this->_columns)) {
return true;
}
}
return false;
}
}
I'm using the following lines to invoke PHPExcel
// Get the selected Excel file, passed from form
$testFile = $_FILES['upload_test']['tmp_name'];
// Identify the file type of the selected file
$inputFileType = PHPExcel_IOFactory::identify($testFile);
// Create a reader object of the correct file type
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
// Instantiate the filter class and apply it to the reader object
$filterSubset = new ReadFilter(1,1000,range('A','Z'));
$objReader->setReadFilter($filterSubset);
// Load the selected file into the reader
$objWorkbook = $objReader->load($testFile);
I am retrieving data from the resulting worksheet object using this syntax:
$someValue= $objWorkbook->getSheet($idx)->getCell('B11')->getCalculatedValue();
I'm sure I'll have other questions as I go, but my initial one is about invoking the function. If I change the above line from:
$filterSubset = new ReadFilter(1,1000,range('A','Z'));
to:
$filterSubset = new ReadFilter(1,1000,range('A','AA')); //Last column changed
the entire read fails. I actually only need calculated values from column B, but that column has references as far over as column AS, so I need to read them as well. Can someone please tell me how to use this function to read past column Z, or to modify it? Ideally, what I'd like is to just read the contents of about a dozen columns spread out from B to AS, but I can't figure that out either.
Thanks much for any help.
range('A','AA'); is not valid try creating your own custom range
Example
echo "<pre>";
print_r(xrange('AA', 'ZZ'));
Function Used
function xrange($start, $end, $limit = 1000) {
$l = array();
while ($start !== $end && count($l) < $limit) {
$l[] = $start;
$start ++;
}
$l[] = $end;
return $l;
}
See Live Demo
range('A','AA) isn't a valid range.... PHP's range function doesn't assume that AA follows Z. Try using column numbers instead, using PHPExcel's columnIndexFromString() and stringFromColumnIndex() static methods in the PHPExcel_Cell class to convert 27 to AA and vice versa (watch out for the base value 0 or 1 though).

PHP class public parameter as two dimensional array, how?

Ok, so I have a class and I would like to be able to get any trackName (two dimensional array) after initializing an object in another php script. This is a part of the class that is relevant:
class fetchData{
public $artistName;
public $trackName;
public function getArtistTracks(){
$i = 0;
if( $tracks = getTracks() ){
foreach ( $tracks['results'] as $track ){
// $artistName is an array of strings (defined as public)
$name[$this->artistName][$i] = $track['name'];
$i++;
}
}
return $name;
}
// later in the class one other function there is this
function initialize(){
...
...
$this->trackName = $this->getArtistTracks();
}
}
Here is how I thought I could call artistName and trackName from another script:
$temp = new fetchData();
echo $temp->artistName[3]; // this works (returns 'some_artist_name' for example)
echo $temp->trackName[$temp->artistName[3]][1]; // this doesn't work
echo $temp->trackName['some_artist_name'][1]; // this also doesn't work
I tried a few other ways. For example instead of this:
$name[$this->artistName][$i] = $track['name'];
I would put this:
$this->name[$this->artistName][$i] = $track['name'];
without the return in getArtistTracks() and without the line in initialize() but that didn't work also. how can I get these trackNames from within another script?
thank you =)
to close this one up, the function should look like this ($i was in the wrong loop):
public function getArtistTracks(){
if( $tracks = getTracks() ){
$i = 0;
foreach ( $tracks['results'] as $track ){
// $artistName is an array of strings (defined as public)
$name[$this->artistName][$i] = $track['name'];
$i++;
}
}
return $name;
}
$name[$this->artistName ---> [$i] <--- ] = $track['name'];
of course, only if $temp->artistName; is array.

Categories