I hope the title is descriptive, I am stuck so I am going to do my best to describe the issue.
I have a comparison I need to make for bed types on a search I am building. One is a $_POST array from the search form ($array1). It lists the bed types, so for example it would look something like:
array('King', 'Queen', 'Full');
My second array ($array2) is from my CMS's profile information and looks like this:
array(
"field_bed_types" => array(
"und" => array(
"0" => array(
"value" => "King"
)
"1" => array(
"value" => "Double"
)
)
)
)
The more bed types they have selected in their profile (there are 6) the more entries there would be past "1" in $array2.
What I am trying to achieve it to take the search types from $array1 and see if $array2 has all of the bed types listed in referenced in $array1. If not, I am doing a continue; and moving on to the next user profile record in my foreach loop.
In this example above, given that $array2 has only King and Double and $array1 is looking for a King, Queen and Full bed, the search should come back as FALSE and then continue to the next record. My question is, how do I do this?
I hope this makes sense, please let me know if you have any further questions.
Note: Drupal is the CMS in use here, but for all purposes this is still a multidimensional array, I just mention my CMS as a way to say that I don't have a way to change the data structure.
Try this
foreach($array1 as $key=>$type)
{
$return[$key]=false;
foreach($array2['field_bed_types']['und'] as $typeArray)
{
if ($type==$typeArray['value'])
$return[$key]=true;
}
}
$failed=false;
foreach($return as $match)
{
if($match==flase)
{
$failed=true;
}
}
if($failed==false)
{
// do stuff if passed
}
Related
Ive come upon the following code and having trouble deciphering its use.
(changed up the variable names a bit for simplicity)
$fooo = array(
'dog' => array('pages', 'home'),
'cat' => array('users', 'login'),
'bird' => array('users', 'reset', 1),
);
I am familiar with associative arrays but have not seen this "nested array" implementation before.
Is this code creating an array of arrays?
For example, $fooo['dog'] returns an array where $dog[0]='pages' and $dog[1]='home'
That seems wrong.
Yes, this is an array of arrays. But it perhaps may be more accurate to describe it as an associative array with an indexed array for every value.
The following can be done with it:
$fooo['dog'] // gets array("pages", "home")
$fooo['bird'][0] // gets "users"
$fooo['cat'][1] // gets "login"
$fooo['cow'] = array('x', 'y'); // adds another value to the outer array
$fooo['bird'][] = 2; // $fooo['bird'] now equals array('users', 'reset', 1, 2)
There is nothing wrong with this code, but your example is lacking practicality. There is plenty of code that uses such structures though. For example, a logical representation of a menu with sub-menus on a website (which seems like the source of your sample), this data structure can then be looped to generate an HTML/CSS menu.
I'm trying to do a sort in my WP_Query on a custom field. The custom field contains strings such as "E100", "E500" and "E123b". I would like to sort numerically on these values, i.e. sort on the custom field as if the characters weren't there.
My query looks like this:
$subpages = new WP_Query(array(
"post_type" => "page",
"meta_key" => "[customFieldNameHere]",
"orderby" => "meta_value_num",
"order" => "ASC",
"posts_per_page" => 5000
));
But it doesn't work. It does some sort of sort, but it's not numerical. Is it possible to strip all characters/letters from the field, and then do a numerical sort on the remaining values, or is there some other way to solve this?
You can't sort a string with letters as if it were all numbers. If you try you will get a alphanumerical sort-- more or less what you'd do if you were alphabetizing something but it makes numbers look odd because it matches up all the first characters, then the second, and so on making numbers look like:
1
10
101
2
20
I don't know of anything built into MySQL that will do what you want, nor does WP_Query have any such feature. The best solution I have is to pull your results unsorted, and sort them later. You want to pull unsorted so the database doesn't do extra work.
$subpages = new WP_Query(array(
"post_type" => "page",
"meta_key" => "[customFieldNameHere]",
"posts_per_page" => 5000
));
$sorted = array();
foreach ($subpages as $s) {
$kname = preg_replace('/[^0-9]+/','',$s->customFieldNameHere]);
$sorted[$kname] = $s;
}
// you may need
// ksort($sorted);
var_dump($sorted);
One problem is going to be collisions. If you end up with two matching $knames you will clobber data, and frankly, that seems pretty likely if you have a lot of data.
I ended up removing the leading E from all strings. Doesn't really solve the original problem, with numerical sorting of strings, but at least it works now.
I am seeking for someone's knowledge out here.
Right now, I would need to merge several arrays into a bigger one, but all of those arrays depend on a function.
This function returns a numeric array containing different quantities of numbers between 1 and 7 :
function Possible($i, $j, $grid)
$possible = Possible($i, $j, $grid)
I'm working with a grid, and the function returns a different array for every case of the grid. What I would like to do is to merge those 7 arrays into another one. Some numbers may be present more than once in this big array, but I want it this way.
I tried using for loops, while loops and some other techniques, but nothing worked. In this case, it is not possible to manually define every array, since they change depending of what is contained in the grid and there are too many. It has to be done automatically, and this is where I get stuck.
for ($jj=0; $j<7; $j++){
$possRow = array_merge( ###what do I add here or what do I change in this code to make everything work###
Thank you if someone can help me out!
Etpi
hope this help:
$biggerOneArray = array();
for($k=0;$k<7;$k++) {
$biggerOneArray[] = Possible($i,$j,$grid);
}
Then you can check your bigger array, may contains all arrays of the iterations of the loop (7 arrays merged).
var_dump($biggerOneArray);
The output should be this:
array(
(int) 0 => array(
'key' => 'value',
'key2' => 'value2'
),
(int) 1 => array(
'key3' => 'value3',
'key4' => 'value4'
)
)
etc...
I'm sorry but your description isn't very clear. But just to get you started you might look at this solution.
function Possible($i, $j, $grid) {
// some code ... e.g. $array[] = "some data";
return $array;
}
By creating a small array for each grid and returning it using return $array you get a few little arrays which you can inturn place into a for loop to merge it into one larger array. However i believe the var $jj must have some meaning in the function it self as well.
for($jj=0;$jj<7;$jj++) {
$merged_array[$jj] = Possible($i,$j,$grid);
}
Maybe if you descripe your problem a little more and post an exmple of the array's your working with i can give you a better answer.
Ultimate Goal
Is to make something like Magento offers - basically a logic builder, and as shown by this post on Stackoverflow: jQuery (or any web tool) Nested Expression Builder So far I have made jQuery to build a tree and get the data that I want the builder to use, check, and set. Now I just need to parse the checks and add it into various places in a script I'm making - but I am unsure how to process it dynamically so that these checks can be performed, which will lead to some actions occurring/data being changed automatically.
Maybe we can call this dynamic expression processing?
Original Post
Forgive me, I know what I would like to do, but have little idea how to do it - so I'm looking for some inspiration. I have allowed a multidimensional array to be generated, and the array would contain certain 'commands' and logic functions, and when a condition is true it is executed.
In it's most basic form, the array would contain a set of if statements, where if the statement were true, then would would proceed to the next array item and go down a level, if it were false, then you'd proceed to the next array item with no children (an unmarried sibling, i guess we could call it). Once there is nothing left to process, since nothing is true, then nothing would happen.
I'd imagine that maybe the best way to 'feed' the data in would be via XML - though would this be possible, I mean, to keep going deeper, else go down, essentially until there is a true condition?
Basically, the array takes the following form (though I not 100% sure I've written it correctly, but I think it looks right :s):
[0][0] => array('function' => 'if', 'check' => 'day', 'condition' => 'equals', 'value' => '3');
[0][1][0] => array('function' => 'set', 'name' => 'date_day', 'value' => 'wednesday');
[1][0] => array('function' => 'if', 'check' => 'day', 'condition' => 'equals', 'value' => '4');
[1][1][0] => array('function' => 'set', 'name' => 'date_day', 'value' => 'thursday');
So the above would be - if day=3, then set date_day as wednesday; else if day=4, then set date_day as thursday
Which I'd imagine would correspond to (though i have no idea if you can sub item):
<items>
<item>
<function>if</function>
<check>day</check>
<condition>equals</condition>
<value>3</value>
<item>
<function>set</function>
<name>date_day</name>
<value>wednesday</value>
</item>
</item>
<item>
<function>if</function>
<check>day</check>
<condition>equals</condition>
<value>4</value>
<item>
<function>set</function>
<name>date_day</name>
<value>thursday</value>
</item>
</item>
</items>
Which would basically make the following statements in a function of some sort:
function ($current_data){
LOOP
if(FUNCTION == "if"){
if(CHECK CONDITION VALUE){
**go to next item deeper in the chain**
} else {
**go to sibling item**
}
} else if(FUNCTION == "set"){
define(NAME, VALUE);
}
ENDLOOP
}
I know the above can be done using the date() function, but this is a very basic example. Another example could involve check to see if the colour entered was red, and if it were, then set something based on this colour, else do something else if it were blue. Another could be to set the template to be for US visitors if the US flag was clicked on. The point is that it could basically fulfil any action and do a check and give a result - basically like programming - but where the function data is feed in by PHP or XML
I'm sure there must be something out there that can accomplish this, but I just have no idea were to start exactly, so any assistance would be great - and yes I know there could be some security concerns, but I plan on having checks in place checking that the checks, conditions, values, etc are safe (so this needs to be able to be factored in).
Many many thanks!
Okay JSON vs. XML aside, here's how I would process that array...
$array = xmldecode($xml);
$resultFound = false;
$i = 0;
while(!$resultFound && $i < count($array)) {
if (myFunction($array[$i]) {
$resultFound = true;
}
$i++;
}
if (!$resultFound) {
// error condition
}
function myFunction($array) {
$function = $array[0]['function'];
switch($function) {
case 'if':
$checkVariable = $array[0]['check'];
$condition = $array[0]['condition'];
$checkValue = $array[0]['value'];
switch($checkVariable)
case 'day':
switch($condition) {
case 'equals':
if (GLOBAL_DAY == $checkValue) {
return myFunction($array[1]);
} else {
return false;
}
break;
case 'less than':
if (GLOBAL_DAY < $checkValue) {
return myFunction($array[1]);
} else {
return false;
}
break;
}
break;
}
break;
case 'set':
$setVariable = $array[0]['name'];
$setValue = $array[0]['value'];
switch($setVariable) {
case 'date_day':
GLOBAL_DATE_DAY = $setValue;
return true;
break;
}
break;
}
}
Your problem is very similar to that of form validation, so I would look at some popular jQuery form validation plugins or MVC frameworks like CakePHP. These typically all have stock building blocks for the most common validation rules that the user can easily put together and pass specific arguments to to cover most scenarios.
The notable difference between your problem and these examples is that form validation frameworks are aimed at developers, so they can simply write custom functions if they need to glue multiple rules together to form a more complex rule. However, you can still achieve something that works for probably 98% of all use cases by doing something like:
$offers = array(
'pet feed sale' => array(
'category' => array(1, 2, 3)
'total' => '>100',
'weekday' => array('mon', 'wed')
'set' => array(
'discount' => 80
'shipping' => 0
)
),
'medication sale' => array(
'category' => 4
'date' => '2012-1-28',
'set' => array(
'discount' => 50
)
)
);
And if the user needs apply more complex pricing structures then they could, for instance, break the "pet feed sale" rule into 3 offers, one for dog food, one for cat food, and one for fish food. There might be more repetition, but it makes it much easier to implement than a full parser.
Also, most non-programmers probably handle repetition a lot better than complicated logic and control flow.
I have the below array..
<?php $arrLayout = array(
"section1" => array(
"wComingEpisodes" => array(
"title" => "Coming Episodes",
"display" => ""
)
));
?>
Then I want to check if wComingEpisodes is in the array so..
<?php if (in_array( "wComingEpisodes" , $arrLayout )) {
echo "CHECKED";}
?>
However its returning nothing even though it is in the array. Do I need to do something different because of the multiple arrays or where is my mistake?
in_array tests for values, not keys. It also does not test nested values.
$arrLayout = array(
"section1" => array(
"wComingEpisodes" => array(
"title" => "Coming Episodes",
"display" => ""
)
));
echo array_key_exists(
"wComingEpisodes",
// this is the array you're actually looking for
$arrLayout['section1'] )?'exists':'does not exist';
you're getting the correct result according to the documentation.
if you want to search an multidimensional array recursive, take a look at the user contributed notes, where you can find examples like this, that show how to do a recursive search (which seems to be what you're looking for).
EDIT:
i just noticed you're trying to find out if a specific key exists: in this case, you'll have to use array_key_exists (like in_array, this also doesn't do a recursive search, so you'll have to do something like this).
in array searches array values.
the string, "wComingEpisodes", is the key of the value
you may want to try using array_key_exists()
In_array isn't recursive by nature so it will only compare the value you give it with the first level of array items of the array you give it.
Thankfully you're not the first with the problem so heres a function that should help you out. Taken from php.net in_array documentation
function in_arrayr($needle, $haystack) {
foreach ($haystack as $v) {
if ($needle == $v) return true;
elseif (is_array($v)) return in_arrayr($needle, $v);
}
return false;
}
http://www.php.net/manual/en/function.in-array.php#60696