I have been searching for a simple answer, but it just doesn't exist, or I don't know how to ask the right questions, to gain the right answers.
Here is the simple to understand question:
I have a big multi-dimensional array, as illustrated here::
$dataFile = array (
array(
array(
data => 'infohere_01',
)
),
array(
data => 'infohere_02',
)
),
etc etc say up to infohere_125 and beyond...
I want to BREAK up the individual arrays creating a simple to manage .php files - using stupid logic ie KISS I thought this would do it. By using include, then stepping through all the seperate .php snippets to make a BIGGER array...
<?php
$dataFile = array (
include '/datafile_01.php';
include '/datafile_02.php';
);
?>
etc etc to include up to and above '/datafile_125.php';
with each include '/datafile_01.php';
being just::
<?php
array(
array(
data => 'infohere_01',
)
),
?>
Not the most elegant way to do it - as it doesn't work...
I cannot find a simple solution. I find complex solutions that do not apply to a simple need.
OK, sorted it now using KISS
Keeping it stupid simple!
Breaking it down into the basics, you find a solution - the complexity of 3d arrays, causing complexity itself, but with additional errors between 2d/3d coding using ), and/or ); there was a compounding of errors going on.
The 2 comments made, both gave a indication towards solving the problem, using RETURN and a loop to include the includes, but the real gem came from further research.
I quote:
Thanks for your help everyone. I found the answer, and I feel pretty
silly: Adding to 3D arrays is as easy as adding to regular arrays!
$users[] = $newuser;
That's bloody it! Amazing, huh? If $users is a 3D array, and $newuser
is an array, it just adds it to the 3D array like I need it to. When
all else fails, try the simplest thing you can think of! Oh well, the
5-6 hours I spent researching this
answered some questions I'll need to take care of later, and I
learned a ton while at it.
Source: [http://www.v7n.com/forums/coding-forum/49651-php-appending-multidimensional-arrays.html][1]
OK so what have I created::
Simple 2D arrays for each file
that is then created by adding to a 3d array as follows!
$shop = array();
$shop[] = include 'Catalogue_ARRAYS/Fire-and-Rescue-Tools_2009.php';
$shop[] = include 'Catalogue_ARRAYS/Insulated-Digging-Tools_2013.php';
Simple really - typical KISS
The 2d arrays / Include.php files are constructed as follows, using RETURN array( rather than $foo = array(::
NOTE:: the use of ); rather than ), which was the MISTAKE!
<?php
return array(
array(
data => 'infohere_01',
)
**);**
?>
That's it SOLVED!
Thanks to all of you who have contributed. We where nearly alright, but sods-law a mini mistake here and there with ' and ; kills things dead.
Thanks again
If you can have some variable declaration inside each of your include '/datafile_01.php':
<?php
$foo = array(
array(
data => 'infohere_01',
)
),
?>
Then you would be able to merge all your include files with something like this, and thus building your big array:
<?php
$dataFile = array();
foreach($includeFiles as $file)
{
include($file);
$dataFile[] = $foo;
}
?>
Included data file should contain:
<?php
return array(
array(
data => 'infohere_01',
)
);
Related
I have a very complex array that I need to loop through.
Array(
[1] => Array(
[1] => ""
[2] => Array(
[1] => ""
[2] => Array(
[1] => ""
)
)
)
)
I can't use nested loops because this array could contain hundreds of nested arrays. Also, the nested ones could contain nested arrays too.
This array presents comments and replies, Where replies could contain more replies.
Any thoughts?
You could use a \RecursiveArrayIterator, which is part of the PHP SPL, shipped non-optional, with the PHP core.
<?php
$arr = [
'lvl1-A' => [
'lvl2' => [
'lvl3' => 'done'
],
],
'lvl1-B' => 'done',
];
function traverse( \Traversable $it ): void {
while ( $it->valid() ) {
$it->hasChildren()
? print "{$it->key()} => \n" and traverse( $it->getChildren() )
: print "{$it->key()} => {$it->current()}\n";
$it->next();
}
}
$it = new \RecursiveArrayIterator( $arr );
$it->rewind();
traverse( $it );
print 'Done.';
Run and play this example in the REPL here: https://3v4l.org/cGtoi
The code is just meant to verbosely explain what you can expect to see. The Iterator walks each level. How you actually code it is up to you. Keep in mind that filtering or flattening the array (read: transforming it up front) might be another option. You could as well use a generator and emit each level and maybe go with Cooperative Multitasking/ Coroutines as PHP core maintainer nikic explained in his blog post.
ProTip: Monitor your RAM consumption with different variants in case your nested Array really is large and maybe requested often or should deliver results fast.
In case you really need to be fast, consider streaming the result, so you can process the output while you are still working on processing the input array.
A last option might be to split the actual array in chunks (like when you are streaming them), therefore processing smaller parts.
The case is quite complex, as you have to loop, but you can't or don't want to for some reasons:
... that I need to loop through
and
I can't use nested loops because this array could contain hundreds of nested arrays
It means you have to either handle your data differently, as you can pack that huge amount of data to be processed later.
If for some reasons it's not an option, you can consider to:
split somehow this big array into smaller arrays
check how does it work with json_encode and parsing string with str_* functions and regex
Your question contains too many things we can't be sure e.g. what exactly these subarrays contain, can you ignore some parts of them, can you change the code that creates huge array in first place etc.
Assuming on the other hand that you could loop. What could bother you? The memory usage, how long it will take etc.?
You can always use cron to run it daily etc. but the most important is to find the cause why you ended up with huge array in the first place.
I am currently trying to figure out how to save a indexed array to a field in my database. That said, I know an array can't be saved to a database, but you can serialize it or implode it and then save. Im not sure which one I should be using though. I don't want a collection of items to be saved in just one cell. I need the list of items to be saved one by one in the column. So my question is do I need to be using the serialize method, implode or something else? Here is a glimpse of my code and the array I am trying to save.
public function findPolicyIds($coverageId = null) {
$policyid = $this->Policy->find('all', array(
'recursive' => -1,
'conditions' => array('Policy.coverage_id' => $coverageId),
'fields' => array('Policy.id')));
foreach($policyid as $id) {
$all[] = $id['Policy']['id'];
}
return $all;
}
Array
(
[0] => 5202834f-111c-4a76-8b33-1ed8ae78509d
[1] => 5202834f-2ba8-4957-91db-1ed8ae78509d
[2] => 5202834f-356c-49a1-beeb-1ed8ae78509d
[3] => 5202834f-3b40-453f-a491-1ed8ae78509d
It depends.
This is probably the best answer to give you.
Do whatever you like, as long as it doesn't magically corrupt the data between write and read.
Lemme take a moment to explore a few options on your behalf.
var_export() - might not be the best idea, securitywise
serialize() - seems straightforward
implode() - seems straightforward
json_encode() - seems straightforward
There are probably other, more obscure, options available. You could even build up complex data sets with XML, if you like.
Alternatively, why not normalize the schema and add a new table to present that collections of array-data ? Normalization tends to save your bacon in the future.
This is probably considered a really silly question, but I'm in the process of putting together a simple template system for a website and am trying to keep track of my variable usage and keep everything neat and tidy.
Can you tell me if there is any advantage/disadvantage to the following methods:
simple var:
$tpl_title = 'my title'
$tpl_desc = 'my text'
array:
$tpl['title'] = 'my title'
$tpl['desc'] = 'my text'
Object:
$tpl->title = 'my title'
$tpl->desc = 'my text'
I like the object method the best as it looks clean when echo'd within html as opposed to arrays and afaik it can be used in an array-like way? However, what I want to know is whether using objects in this way is considered bad practice or introduces unneccesary overheads?
In ideal scenarios every variable should belong to an object, other than the variables local to methods for temp purposes. However we don't live in an ideal world and specially our programming languages are far from it. Based on what the situation is, choose the best way to go about it to make your life easier. If you are using things for templates, generally you keep all the data in an array and extract the array to get stand alone variables.
So yeah, the object method is the nicest, try to make it happen as much as you can without spending crazy amounts of time in doing it.
Also if you love objects and want to have the neat -> way of doing it, you can do
$object = (object)$array;
That would convert your array to an object.
Hope that helps.
I would consider it unnecessary overhead. Doing what you are talking about in an object-oriented way only means that inside your class you will have done nothing more than create a bunch of variables, just as you specified in your first example.
The array is the best way to go in my opinion. You are only using one variable, and you can also integrate it into your Class. So, instead of $tpl->title, you may have $tpl->text['title'].
Arrays
I would suggest on the backend part, keep everything stored in an array. This allows you to have only one variable to keep track of, and once you pass it to the frontend, you can extract() the array, to convert them into simple variables.
Syntax
Using extract() simplifies the syntax on the FrontEnd, which means you will only always have $varibles in the template.
On the backend you would set
$array['title'];
Which once extracted would in the template be
$title;
Example of a backend function
protected function fetch($template, $data = null)
{
if (!$this->isTemplate($template)) {
throw new Exception("Template file $this->_templatePath$template not found");
}
ob_start();
if (is_array($data)) {
extract($data, EXTR_SKIP);
}
require $this->_templatePath . $template . EXT;
return ob_get_clean();
}
In the end they are the same, It depends on the preference, although I would use arrays or objects because you can group variables in there, so you have things better sorted out.
Despite the objects method works I think it's not the natural intended use for it.
So I would say arrays!
Also, there are tons of php native functions you can use with arrays, like array_map() or array_filter() array sortings and etc etc...
In my opinion the cleanest way to set it up is in array like this:
$tpl = array (
'title' => 'my title',
'desc' => 'my text'
);
You can combine it with Zane's answer also.
All the best!
$tpl = array (
'title' => 'my title',
'desc' => 'my text'
);
Like Goran said, with the bonus that you could store these arrays in an ini file later and extract them as needed with parse_ini_file
Could be important if you want to permit users to write to their own ini file.
arrays and objects are useful in case if you want to reset bulk of variable data after use it.
you can simply unset the array or destroy the object instead of unset range of variables use in a code.
Other than this arrays and objects have more symmetry in code and explanatory than normal variables
So, I've decided to get my feet wet with MongoDB and love it so far. It seems very fast and flexible which is great. But, I'm still going through the initial learning curve and as such, I'm spending hours digging for info on the most basic things.
I've search throughout the MongoDB online documentation and have spent hours Googling through pages without any mention of this. I know Mongo is still quite new (v1.x) so it explains why there isn't much information yet. I've even trying looking for books on Mongo without much luck. So yes, I've tried to RTM with no luck, so, now I turn to you.
I have an Array of various Hashtags nested in each document (ie: #apples, #oranges, #Apples, #APPLES) and I would like to perform a case-insensitive find() to access all the documents containing apples in any case. It seems that find does support some regex with /i, but I can't seem to get this working either.
Anyway, I hope this is a quick answer for someone.
Here's my existing call in PHP which is case sensitive:
$cursor = $collection->find(array( "hashtags" => array("#".$keyword)))->sort(array('$natural' => -1))->limit(10);
Help?
I suspect your query is not returning what you really want...
If you do
db.col.find( { some_array_field: ["item1", "item2"] } );
then it will only match documents that have EXACTLY these two items in some_array_field. So if there is a document with [item1, item2] hashtags it will match, but a document with [item1, item2, item3] tags won't match.
You could use the $all argument as described in this post:
How do you do an AND query on an array in mongodb?
e.g.
db.col.find( { some_array_field: { $all : ["item1", "item2"] } } );
or:
db.col.find( { some_array_field: "item1", some_array_field: "item2" } );
This distinction of complete-document-match and partial-match was really confusing in MongoDB for me at first.
here is an example for case insensitive search in mongodb with php
$search_string='baR';
$searchQuery = array(
'$or' => array(
array(
'field1' => new MongoRegex("/^$search_string/i"),
),
array(
'field2' => new MongoRegex("/^$search_string/i"),
),
)
);
$cursor = $customers->find($searchQuery);
Hopes this help any.
Is there any thing wrong with this array?
$selects = array(
"getmoney1" => $money["Dimes"],
"getmoney2" => $money["Nickels"],
"getmoney3" => $money["Quarters"]
);
I am learning, and I want to know more, and how to do it right.
There is nothing wrong with this declaration. However it does assume the existence of an array named $money, and that $money["Dimes"], etc. are all set.
Syntactically nothing wrong, but what on earth would the point of it be?
The original array $money would be easier to work with, I suspect.
But I agree with the commenter above - not enough information to go on.