Arrays, foreach, adding string to array trouble - php

if ($_POST['op_ep_cat'] == 'op_single_ep')
{
$ep_place = $_POST['the_place'];
$eps_array = array();
array_push($eps_array, $ep_place);
}
else if ($_POST['op_ep_cat'] == 'op_category') {
$cat_site = $_POST['the_place'];
$taken_cat_site = file_get_contents($cat_site);
if (preg_match_all('#<div class="content_ep"><a href="(.+?)"#si', $taken_cat_site, $eps_array));
else if (preg_match_all('#<div class="postlist">\s*<a href="(.+?)"#si', $taken_cat_site, $eps_array));
}
foreach(array_reverse($eps_array[1]) as $eps_match)
{
echo 'Arughh!';
}
The above works for the 'op_category' perfectly, but not for the 'op_single_ep'... So basically $ep_place needs to be apart of the $eps_array[1], if possible, somehow.. Hopefully any of this makes sense!
I appreciate any help!

try that
$eps_array = array(1 => array($_POST['the_place']));
but whole code is just weird

$eps_array[1] is not array, is element of $eps_array
You can make array
$eps_array = array(1=>array());
array_push($eps_array[1], $ep_place);
Try to read manual about What is array

it'd be $eps_array[0] for the op_single_ep version. Remember, PHP arrays have 0-based indexes.

Try this
if ($_POST['op_ep_cat'] == 'op_single_ep')
{
$ep_place = $_POST['the_place'];
$eps_array = array();
$eps_array[1] = array();
array_push($eps_array[1], $ep_place);
}

Related

Searching a value inside a multidimensional array in php

I'm currently using this:
foreach($hash_list as $key => $val){
if(in_array($search_this,$hash_list[$key])){
echo 'Found value in key '.$key;
break;
}
}
To find $search_this in this:
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
Is there a better way to find the key for this situation? $hash_list has about 500 arrays with 5 elements each inside.
Deadpool: #Sergey No php built-in function that I'm missing?
I dont think so. But I think it's may be little faster, but I'm not sure
$hash_list = array();
$hash_list["a"] = "dfv8p, hi8o7, d2l9f, qhx13, c7duz";
$hash_list["b"] = "pdsyt, jjivh, nj12b, 19tm2, ltsqp";
$hash_list["c"] = "67s6q, tlwu7, c9p77, 7airj, j7tej";
foreach($hash_list as $key => $val){
if(strpos($hash_list[$key], $search_this) !== false) {
echo 'Found value in key '.$key;
break;
}
}
You can use user build functions like this
function isValueExist($hash_list,$needle){
foreach($hash_list as $val){
if(in_array($needle,array_values($val))) return 1;
}
}
Usage :-
if (isValueExist($hash_list,"d2l9f")){
//DO you things here
}
You can make use of list() too ;)
<?php
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
$searchParam = "67s6q";
while(list($a,$b) = each($hash_list))
{
if(in_array($searchParam,$b))
{
echo "$searchParam found in $a\n";
}
}
OUTPUT :
67s6q found in c

Recursively add to an array

I'm struggling to understand a problem that i've got with recursion where by I am traversing down a hiearchy in only one direction and adding all the children of each parent to an array.
However I can't quite work out the best way to continuously add to that array while using recursion.
Here is what my function looks like so far. I'd appreciate it hugely if someone could push me in the right direction with this.
function getTaxChildrenList($cat, $data){
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
if(count($next)){
$result = array();
foreach($next as $next_key => $next_level){
$result[$next_level->term_id] = $this->getTaxChildrenList($next_level->term_id, $result);
}
}
return $result;
}
I now have the structure being returned as I want but need to actually add the objects of each of these children to the key which i'm guessing might be my base case.
Screenshot -> http://cl.ly/image/1z1v2S243f3H
So perhaps you need something like this:
function getTaxChildrenList($cat){
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
$result = array();
if(count($next)){
foreach($next as $next_key => $next_level){
$result[$next_level->term_id] =
array("data" => $next_level->something,
"children" => $this->getTaxChildrenList($next_level->term_id));
}
}
return $result;
}
Is it something like that?
This should do the job
function getTaxChildrenList($cat) { //no second parameter
$next = get_terms('location_types', 'orderby=count&hide_empty=0&parent='.$cat);
$result = array();
//base case would be count($next) == 0
if(count($next)){
foreach($next as $next_level){
//add recursively arrays
$recur = $this->getTaxChildrenList($next_level->term_id);
if(count($recur) == 0)
$result[$next_level->term_id] = $next_level;
else
$result[$next_level->term_id] = $recur;
}
}
return $result;
}

If true use foreach loop, else use while

I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}

is this code improvable?

Currently my mind is under heavy pressure and I can't stay a long time focusing on one single issue, I am pretty sure that the way I made it is basic and can be improved to make it smaller and easier (more professional maybe ?) code;
<?php
$intro_id = rand(1,2);
if($intro_id == 1 && !empty($options['hidden_intro_one'])){
$hidden_intro = $options['hidden_intro_one'];
}
elseif(!empty($options['hidden_intro_two'])){
$hidden_intro = $options['hidden_intro_two'];
}
else{
//back to circle number 1
$hidden_intro = $options['hidden_intro_one'];
}
?>
Partially SOLVED :
the solution was to use array_rand() function like this :
<?php
$random_intro = array($options['hidden_intro_one'],$options['hidden_intro_two']);
$hidden_intro = $random_intro[array_rand($random_intro)];
?>
But if one of the intros is left empty, it will appear empty when you echo the code, while I want to print the other intro (if not empty) instead...
It can certainly be 'improved'. Code can always be improved :) One easy improvement you can always do (more of a habit to teach yourself) is to add a comment about what the code is supposed to do.
Anyway, what (I think) you're trying to do is basically the same as:
$hidden_intro = $options[ array_rand( $options ) ];
<?php
$intros = array(
1 => $options['hidden_intro_one'],
2 => $options['hidden_intro_two']
);
$intro_id = rand(1,2);
$hidden_intro = empty($intros[$intro_id]) ? reset($intros) : $intros[$intro_id];
?>
Although I don't like using reset() as a way to get the first possible value, but you can customize the 'default' value process :)
Something like this maybe:
$intro = array("hidden_intro_one","hidden_intro_two");
$hidden_intro = $options[array_rand($intro)];
Or, if $options only contains hidden_intro_one and hidden_intro_two you could just do:
$hidden_intro = array_rand($options);
EDIT oops, this leaves out the part where it can't be empty.
If $options only contains hidden_intro_one and hidden_intro_two
$hidden_intro = $options["hidden_intro_one"]; // fallback if both are empty
shuffle($options);
foreach($options as $option)
if(!empty($option)){
$hidden_intro = $option;
break;
}
Else
$hidden_intro = $options["hidden_intro_one"]; // fallback if both are empty
$intros = array("hidden_intro_one","hidden_intro_two");
shuffle($intros);
foreach($intros as $intro)
if(!empty($options[$intro])){
$hidden_intro = $options[$intro];
break;
}
This might not necessarily be better though, but it will be if you add more values.
Encapsulate what varies and for the standard problem use an existing function like array_rand:
$intros = get_non_empty_intros_from_options($options);
$hidden_intro = array_rand($intros);
function get_non_empty_intros_from_options($options)
{
$intro_option_keys = array('one', 'two');
$intro_option_key_mask = 'hidden_intro_%s';
$intros = array();
foreach ($intro_option_keys as $intro)
{
$key = sprintf($intro_option_key_mask, $intro);
if (empty($options[$key]))
continue
;
$intros[$key] = $options[$key];
}
return $intros;
}
This method will allow you to use more than one intro.
<?php
//why not make your intro's an array in your options array
$options['hidden_intro'] = array('one', 'two');
//declare your intro variable
$hidden_intro;
//now lets loop our intro's
foreach($options['hidden_intro'] as $intro)
{
if(!empty($intro))
{
$hidden_intro = $into;
break;
}
}
if(isset($hidden_intro))
{
//use your intro here
}
?>
Just for fun, an (almost) oneliner:
$to_be_choosen_keys = array("hidden_intro_one","hidden_intro_two");
$hidden_intro = array_rand(
array_intersect_key(
$options,
array_flip($to_be_choosen_keys)
)
);

Simple way to check an array for "holes" in the keys

I have a simple associative array:
$ar = array( 1=>'foo', 2=>'bar', 5=>'foobar', 8=>'barfoo' )
I need to efficiently find holes in the keys. The keys are guaranteed to be integers.
findHole($ar)
> 0
findHole($ar,1)
> 3
findHole($ar,5)
> 6
what is the easiest way to do this?
Try this:
function findHole($array, $key=0) {
while (array_key_exists($key, $array)) {
$key++;
}
return $key;
}
The desired behavior of your findHole function isn't 100% clear to me, but the following code snippet will give you an array that has all the "missing" indexes.
$ar = array( 1=>'foo', 2=>'bar', 5=>'foobar', 8=>'barfoo' );
$keys = array_keys($ar);
$missing_indexes = array_diff(range(0,max($keys)), $keys);
print_r($missing_indexes);
Depending on your use case this may or may not be less efficient. It's using multiple function calls and arrays are passed around by value by default, but those functions are operating at native code speeds, while solutions using loops are going to be running at PHP speed.
Use case, benchmark, etc.
All holes:
function GetHoles($arr)
{
$holes = array();
$max_value = max(array_keys($arr));
for($i = 0; $i < $max_value; $i++)
{
if(!in_array($i, $keys)) $holes[] = $i;
}
return $holes;
}
if you just want to condense the array, try this:
function FlattenArray( $o )
{
$res = array();
foreach($o as $v)
{
$res = array_merge($res, FlattenArray($v));
}
return $res;
}

Categories