I have this script from a free website file. Here is the subject script:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
How to get the value of ID and echo it?
When you clean up the code, it’s easy to see how to access the ID value:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
if ($a == 'ID') {
echo $a1;
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
Just adding the check for ID will work:
if ($a == 'ID') {
echo $a1;
}
EDIT And if you want to access it outside of the foreach loop, just do this. I have an if conditional to just check if the value exists.
if (array_key_exists('ID', $auth) && !empty(trim($auth['ID'])) {
echo $auth['ID'];
}
Or, since your foreach loop is creating $results you can access that value this way instead:
if (array_key_exists('ID', $results) && !empty(trim($results['ID'])) {
echo $results['ID'];
}
Related
$printArr = recursive($newArray); //calls recursive function
$data = [];
var_dump($data);
var_dump($printArr);
function recursive($array, $level = 0)
{
$searchingValue = 'tableName';
foreach($array as $key => $value)
{
//If $value is an array.
if(is_array($value))
{
recursive($value, $level + 1);
}
else
{
//It is not an array, so print it out.
if($key == $searchingValue)
{
echo "[".$key . "] => " . $value, '<br>';
$data[] = $value;
}
}
}
}
So I have this function and I am trying to save $value value into $data[] array. But it always returns it empty and I don't know why I can't get $value saved outside the function.
If i echo $value I get what i need but like I've mentioned the variables doesn't get saved in this case - table names.
You need to pass the $data to your recursive function. Also you need to return the $data.
Try this code :
function recursive($array, $level = 0, $data =[])
{
$searchingValue = 'tableName';
foreach($array as $key => $value)
{
//If $value is an array.
if(is_array($value))
{
recursive($value, $level + 1 , $data);
}
else
{
//It is not an array, so print it out.
if($key == $searchingValue)
{
echo "[".$key . "] => " . $value, '<br>';
$data[] = $value;
}
}
}
return $data;
}
You can't access variable $data, which is outside the function, from the function. You need to pass it by reference or return it. Small example
<?php
$a = 1;
// Your case
function b() {
$a = 4;
return true;
}
// Passing by reference
function c(&$d) {
$d = 5;
return true;
}
// Using return
function d($d) {
$d = 6;
return $d;
}
b();
var_dump($a);
c($a);
var_dump($a);
$a = d($a);
var_dump($a);
https://3v4l.org/UXFdR
I'm trying to make the following work:
<?php
$item1 = A;
$item2 = B;
$item3 = C;
$array = array($item1, $item2, $item3);
function myFunction () {
if ($item = "A") {
echo "Alpha ";
}
elseif ($item = "B") {
echo "Bravo ";
}
elseif ($item = "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ();
}
?>
The intended effect is that for each item, if the value is A, echo "Alpha", B echo "Bravo" and C echo "Charlie".
However, the output is as follows:
Alpha Alpha Alpha
There were no errors in the error log, so I'm guessing I must have made some kind of mistake not pertaining to syntax. I added an echo $item; before myFunction, and the output is as follows:
AAlpha BAlpha CAlpha
Which means that the $item has been correctly assigned A, B and C. Why doesn't myFunction work like intended?
Thanks in advance!
1) The = is the assignment operator and may not be used for comparisons. Try == or === instead.
2) You assigned $item1 = A but compared $item = "A". However A and "A" are usually different.
3) You didn't pass $item to the function.
In the first if statement you assign "A" to $item and then print out "Alpha" “if "A"”.
Your code should probably look something like this:
<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>
Set $item parametar on your function.
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction($item){
if($item == "A"){
echo 'Alpha'.'<br/>';
}
elseif ($item == "B") {
echo 'Bravo'.'<br/>';
}
elseif ($item == "C") {
echo 'Charlie'.'<br/>';
}
}
foreach ($array as $item) {
myFunction($item);
}
Also, are you going to pass the variable to your function or what? Otherwise, as it is right now, it should only output "error."
Your function does not have an argument.
foreach ($array as $item) {
myFunction ();
}
How about passing the $item so that your function can actually work:
function myFunction($item) {
and therefore:
foreach($array as $item) {
myFunction($item);
}
<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>
I have a multidimensional array $array["A"]["B"]["C"]["D"]. The list is longer.
Is there a wildcard that I can use to get ["D"] value in let say ["B"] array?
Something like this, $array["A"]["B"][*]["D"] ?
or $array[*]["B"][*]["D"] ?
Example, I would like to get all prices that were bought on February regardless of the year.
$array[2013][2][23]["ItemName"]["ItemPrice"] .....
If this would work, it would be really wonderful
$array[*][2][*][*]["ItemPrice"]..
any idea?
You could do multiple foreach to loop though every nested array that you want to loop though.
foreach ($array as $a) {
foreach ($a["B"] as $c) {
foreach ($c as $d) {
// Do something with $d
}
}
}
This would be $array[*]["B"][*][*]
Edit: You could combine my suggestion with a while loop.
$innerArray = $array;
while (true) {
foreach ($array as $key => $value) {
if ($key == "D") {
// Do something with this value
} else if (is_array($value)) {
$innerArray = $value;
} else {
break;
}
}
}
Thanks to #Sepehr-Farshid it just crossed my mind that I can use recursive function (Something that I haven't use for quiet a while. So here a example.
$newarray = array();
$tempArray = $oldarray;
$levels[] = 1;
$keys[] = 2;
$levels[] = 4;
$keys[] = "ItemPrice";
$lastLevel =4;
recurArray($tempArray, 0);
function recurArray($array, $level)
{
foreach($array as $key => $value) {
if(array_search($level, $GLOBALS["levels"]) {
$tempKey = array_search($level, $GLOBALS["levels"];
if($key == $GLOBALS["keys"][$tempKey] {
if($level == $GLOBALS["lastLevel"]) $GLOBALS["newarray"] = $value;
else recurArray($value, $level + 1);
}
else { return; }
}
else { recurArray($value, $level + 1); }
}
}
this might not be the optimum way, but it will work and can be refined. :D
I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.
I'm searching for a way to show me the different properties/values from given objects...
$obj1 = new StdClass; $obj1->prop = 1;
$obj2 = new StdClass; $obj2->prop = 2;
var_dump(array_diff((array)$obj1, (array)$obj2));
//output array(1) { ["prop"]=> int(1) }
This works very well as long the property is not a object or array.
$obj1 = new StdClass; $obj1->prop = array(1,2);
$obj2 = new StdClass; $obj2->prop = array(1,3);
var_dump(array_diff((array)$obj1, (array)$obj2))
// Output array(0) { }
// Expected output - array { ["prop"]=> array { [1]=> int(2) } }
Is there a way to get rid of this, even when the property is another object ?!
Something like the following, which iterates through and does a recursive diff is the item in the array is itself an array could work:
Des similar work to array_diff, but it does a check to see if it is an array first (is_array) and if so, sets the diff for that key to be the diff for that array. Repeats recursively.
function recursive_array_diff($a1, $a2) {
$r = array();
foreach ($a1 as $k => $v) {
if (array_key_exists($k, $a2)) {
if (is_array($v)) {
$rad = recursive_array_diff($v, $a2[$k]);
if (count($rad)) { $r[$k] = $rad; }
} else {
if ($v != $a2[$k]) {
$r[$k] = $v;
}
}
} else {
$r[$k] = $v;
}
}
return $r;
}
It then works like this:
$obj1 = new StdClass; $obj1->prop = array(1,2);
$obj2 = new StdClass; $obj2->prop = array(1,3);
print_r(recursive_array_diff((array)$obj1, (array)$obj2));
/* Output:
Array
(
[prop] => Array
(
[1] => 2
)
)
*/
My solution will recursively diff a stdClass and all it nested arrays and stdClass objects.
It is meant to be used for comparison of rest api responses.
function objDiff($obj1, $obj2):array {
$a1 = (array)$obj1;
$a2 = (array)$obj2;
return arrDiff($a1, $a2);
}
function arrDiff(array $a1, array $a2):array {
$r = array();
foreach ($a1 as $k => $v) {
if (array_key_exists($k, $a2)) {
if ($v instanceof stdClass) {
$rad = objDiff($v, $a2[$k]);
if (count($rad)) { $r[$k] = $rad; }
}else if (is_array($v)){
$rad = arrDiff($v, $a2[$k]);
if (count($rad)) { $r[$k] = $rad; }
// required to avoid rounding errors due to the
// conversion from string representation to double
} else if (is_double($v)){
if (abs($v - $a2[$k]) > 0.000000000001) {
$r[$k] = array($v, $a2[$k]);
}
} else {
if ($v != $a2[$k]) {
$r[$k] = array($v, $a2[$k]);
}
}
} else {
$r[$k] = array($v, null);
}
}
return $r;
}
Here is a comparison function that I built using the pattern:
function objEq(stdClass $obj1, stdClass $obj2):bool {
$a1 = (array)$obj1;
$a2 = (array)$obj2;
return arrEq($a1, $a2);
}
function arrEq(array $a1, array $a2):bool {
foreach ($a1 as $k => $v) {
if (array_key_exists($k, $a2)) {
if ($v instanceof stdClass) {
$r = objEq($v, $a2[$k]);
if ($r === false) return false;
}else if (is_array($v)){
$r = arrEq($v, $a2[$k]);
if ($r === false) return false;
} else if (is_double($v)){
// required to avoid rounding errors due to the
// conversion from string representation to double
if (abs($v - $a2[$k]) > 0.000000000001) {
return false;
}
} else {
if ($v != $a2[$k]) {
return false;
}
}
} else {
return false;
}
}
return true;
}
Usage:
$apiResponse = apiCall(GET, $objId);
$responseObj = json_decode($apiResponse);
// do stuff ...
if(!objEq($myObj, $responseObj) apiCall(PUT, $myObj, $objId);
Note that the apiCall function is just a mock to illustrate the concept.
Also this solution is incomplete because it does not take into account any key->value pairs that are unique to obj2. In my use case this is not required and could be neglected.
NB: I borrowed heavily from Peter Hamiltons contribution. If you like what I did then please upvote his solution. Thanks!