I have a multidimensional array which has some predictable key and some unpredictable.
An example would be:
$myarray[0] => array ( [prefix-number] => value ... )
$myarray[1] => array ( [prefix-number] => value ... )
The first part of the array will always start at 0 and go up from there... that is by design. The second part of the array has a set prefix which is a label which is predictable but the number after the dash is not. For array entry 0 it could be number 3 or 6. For entry 0 all numbers will be the same. What I'm looking to do is a for statement that will go through each element in the array checking the sub key prefixes but not worry about the number... for example:
for($i = 0; $i < count($myarray); $i++) {
if($myarray[$i]['prefix-'%] == "") {
$error = "error";
}
}
I want the % in there to be a wildcard where the if statement won't worry about what is there just the prefix which is in quotes.
I realize I can use substr on the array key and get just the prefix out but I was hoping that wildcards were allowed in some way.
Thanks for the criticism!
I ended up storing the second key in a variable so it looks like:
$arraykey = key($myarray[$i]);
if($myarray[$i][$arraykey] == "") { ....
Related
I have an array similar to this:
$stuff = array("a"=>"115","b"=>"0","c"=>"1","d"=>"0","e"=>"11","f"=>"326","g"=>"9","h"=>"1","i"=>"12","j"=>"0","k"=>"56");
What I want to do is concatenate the strings of the keys only where they are consecutive and their values are under 10 - note this includes keeping solitary keys with values under 10 too. I don't need to keep the actual values. In other words, the desired result in this case would be:
Array ( [0] => bcd [1] => gh [2] => j)
So there might be just two consecutive keys that need to be joined, or there might be more (eg as many as 5). I'm not sure how to 'look ahead' through the array to achieve this.
You don't need to look ahead but keep the past in mind.
$consecutive = '';
foreach($stuff as $k => $v) {
if ($v < 10) // or what ever condition you need
$consecutive .= $k;
else {
if ($consecutive) $res[] = $consecutive; // if exist add it
$consecutive= ''; // and reset
}
}
if ($con) $res[] = $con; //adding last element if exist as #Joffrey comment
Now $res will be your desire output
Live example: 3v4l
i hace this issue whit two arrays
one array is given by a json like this
array1( [0] => 6, [1] => 1)
and making a query i got this other
array2( [0] => 1, [1] => 1)
I want to compare both arrays and use "if" when numeric values of array1 are less than or equal to array2. Is that possible? like this?
if($array1 <= $array2){do something}
Grettings!
This really depends on what your expected behaviour is, and also the expectations of your two arrays. For the sake of these examples, I'm going to assume that each array is guaranteed to be the same size and you are compairing paired elements (elements from each array at the same index).
If you want to exit the first time a number from array1 is less than its paired element from array2:
for ($i = 0; $i < sizeof($array1); $i++) {
if ($array1[$i] <= $array2[$i]) {
...do something
}
}
If you want to do something if all values of array1 are less than their paired elements from array2:
// Keep track of a flag so we know if we meet our condition once done
$allValuesLessThan = true;
// Check each individual array1 element and its 'paired element' from array2
for ($i = 0; $i < sizeof($array1); $i++) {
// If we break our condition, set our flag and break out of our loop, since we no longer need to check subsequent elements
if ($array1[$i] > $array2[$i]) {
$allValuesLessThan = false;
break;
}
}
// Finally, only do our 'something' if our condition was met
if ($allValuesLessThan) {
...do something
}
I know that if you manually declare the keys in your array, it is considered hash and if it is a self-generated key, it is an array(sequential). So what if I manually declare
$array1 = array(1 => 123, 2 => 312, 3 => 456);
// and
$array2 = array(123,312,456);
Questions:
Is $array1 an array or hash?
Is my idea on hash and array correct?
PHP uses only associative arrays. To determine if an array could be an indexed array from 0 to size - 1 eg an array where elements have been pushed, or added using array[] = x, the only method known is to check if all keys are from 0 to size - 1.
(Note that an array could be built via the "associative" way (ie providing both keys and values), using incremental keys from 0, and there is no way to determine that it was not built using the method given above (push or []), since, anyway, that makes no difference)
$i = 0;
foreach (array_keys($array) as $key) {
if ($key !== $i) break; // Note the !== (not !=)
$i++;
}
if ($i == count($array)) {
// looks like array was built using indexing (see text above)
}
The final test $i == count($array), if true, indicates that all keys where numeric, starting from 0, incremented by 1 for each element, until the last element.
I have an array inside another and I would like to change a value in a key.
//Obtenemos el numero de arrays
$count = array();
for($i = 0; $i < count($passer); $i++)
{
if(array_key_exists($passer[1],$passer[$i])) {
$passer[1] = "hola";
}
$count[] = $passer[$i];
}
//return....
return $count;
I need to change entries where the key is 1 and replace the value.
I have this array output:
array
(
[0]=>array
(
[0]=>81278
[1]=>87364
[2]=>34923
)
[1]=>array
(
[0]=>81278
[1]=>87364
[2]=>34923
)
)
but I get an error:
Warning: array_key_exists() [function.array-key-exists]:
Any idea what this means and what to do about it?
Several things you should change. First of all the way you write your for statement isn't optimal, it will execute the count() function upon every iteration, make it like so
for($i = 0, $c = count($passer); $i < $c; $i++)
Second, your problem. You need to check the key, which in your case is static 1, in the array $passer[$i], so your array_key_exists() function should look like this
array_key_exists(1,$passer[$i])
array_key_exists expects the first parameter to be the key and second the array you wish to inspect
I think you meant to put array_key_exists($passer[1], $passer)
The second parameter has to be an array, but in your example you are passing it the element of an array (which is not an array hence the php warning).
http://php.net/manual/en/function.array-key-exists.php
I've been given a datafile where the original creator used alphabetical rather than numeric values to show order.
For example, if there's ten items, they'd be named:
12342313A
12342313B
12342313C
12342313D
12342313E
...
I need to import these values into a mySQL table that has order as a required int column, and I need to convert the letter to a number.
Is there a function in PHP to get a numeric value for a letter? Or will I need to do a substr to grab the trailing letter, and create an indexed array of letters and just do a lookup against that array?
I'm hesitant to do the simple way above, since I don't know how many objects could potentially exist, and I could need to write an array from A-AAAA or something.
Try converting it from base 36 to base 10 using base_convert(), I.e. base_convert($str, 36, 10). You might need to strtolower it first, and it'll only work if its not case sensitive.
PHP has a simple way to create that array, so you could write a function to figure all that out for you and do something like:
function str_to_num($letters, $max = 'ZZZZZZ') {
$count = 0;
for ($i = 'A'; $i < $max; $i++) {
$count++;
if ($letters == $i)
return $count;
}
}
Then you could do the substr, find the letters at the end, and then pass it into the function:
str_to_num('A'); // returns 1
str_to_num('AB'); // returns 28
str_to_num('AC'); // returns 29
str_to_num('ABC'); // returns 731
Something like that, anyway.
Good luck.
Assuming this is a one-time problem that you've got to correct and won't encounter moving forward, I suggest you use sort to... erm, sort out the problem. Let's say you have all those alpha-numeric order fields in an array, like so:
$vals = array (
'12342313A',
'12342313D',
'12342313E',
'12342313B',
'12342313C'
);
Those are all mixed up, not in order. But, you can call the function sort (docs) on that array and PHP does a decent job of making sense out of it:
print '<pre>Unsorted: ';
print_r($vals);
print '</pre>';
sort($vals);
print '<pre>Sorted: ';
print_r($vals);
print '</pre>';
/*
Unsorted: Array
(
[0] => 12342313A
[1] => 12342313D
[2] => 12342313E
[3] => 12342313B
[4] => 12342313C
)
Sorted: Array
(
[0] => 12342313A
[1] => 12342313B
[2] => 12342313C
[3] => 12342313D
[4] => 12342313E
)
*/
So far, so good. Now, you've got them ordered, and as a bonus you can use the index of the array as your new field in the database. Alter the table and add a field to hold the new value; we'll call this field numeric_order, and in my sample I've called the field that currently holds the alpha-numeric sort data string_order. Loop your sorted array and update the database (for example):
foreach ($vals as $x=>$v) {
$sql = 'UPDATE myTable SET numeric_order = '.($x+1).' WHERE string_order = "'.$v.'"';
}
I add 1 to x in the loop based on the assumption that you don't want anything to have 0 for the order - if that isn't a concern, then you can just use x. This is also predicated on the assumption that no two rows have the same alpha-numeric sort value.
If they do, then all is not lost! Start with your array looking like this:
$vals = array (
3=>'12342313A',
15=>'12342313D',
66=>'12342313E',
101=>'12342313B',
200=>'12342313C'
);
... the numeric keys would represent the unique/primary key of the corresponding row. Instead of sort, which does not preserve keys, use asort (which does preserve keys - docs), and then your loop looks like this:
$ord = 1
foreach ($vals as $x=>$v) {
$sql = 'UPDATE myTable SET numeric_order = '.$ord.' WHERE id = "'.$x.'"';
$ord++;
}
If my base assumption is wrong, and you'll continue to deal with this method of ordering rows, then in my humble view you ought to re-consider your data design.
use ord() with substr and subtract 64. This will set A to 1, B to 2, etc...
From what you have above, it seems like your values (last digit, at least) can be thought as being hex numbers. You can then transform them into decimal numbers through the hexdec function.
http://php.net/manual/en/function.hexdec.php