PHP Array element to string - php

I use PHPExcel to put elements of my Excel file into an array. I then do
print_r($worksheets);
Where $worksheets is the array created through PHPExcel. The output is
Array (
[enquiry] => Array (
[0] => Array (
[0] => 86.141.247.93
)
[1] => Array (
[0] => 188.141.76.143
)
[2] => Array (
[0] => 2.29.20.161
)
)
)
What I need to do is pass each of these IPs as a String to a function. So what I am trying is this
foreach($worksheets as $ip) {
$count = 0;
if ($SpamProtecter->CheckIP($ip[$count][0])) {
print_r("SPAM");
} else {
print_r("GOOD");
}
$count++;
}
The problem I have is that it only prints out one result. How can I pass each array element as a String to CheckIP?
Thanks

You have an intermediate level in your array. Remember, foreach iterates over the top level of elements. You have 3 tiers here
foreach($worksheets['enquiry'] as $ip) { //iterate tier 1
if ($SpamProtecter->CheckIP($ip[0])) { //grab tier 3
print_r("SPAM");
} else {
print_r("GOOD");
}
}

Your $worksheets array only has a single key: enquiry, which is why you're only getting a single result output. Try this:
foreach($worksheets['enquiry']) as $ip) {
if($SpamProtector->CheckIP($ip[0]) {
// ...
I think you can also get rid of that inner $count variable since it is not used anymore.

This could work
foreach($worksheets['enquiry'] as $ip) {
if ($SpamProtecter->CheckIP($ip[0])) {
print_r("SPAM");
} else {
print_r("GOOD");
}
}

array_walk works well in situtations where you want to perform an action on each element in an array.
array_walk($worksheets["enquiry"],
function ($a) use ($SpamProtecter) {
echo $SpamProtecter->CheckIP($a[0])?"GOOD":"BAD";
});

Related

Getting an element from array in PHP

With the following array, how would I just print the last name?
Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.
$array = Array
(
[0] => Array
(
[name] => FirstName
[value] => John
)
[1] => Array
(
[name] => LastName
[value] => Geoffrey
)
[2] => Array
(
[name] => MiddleName
[value] => Smith
)
)
I would normalize the array first:
$normalized = array();
foreach($array as $value) {
$normalized[$value['name']] = $value['value'];
}
Then you can just to:
echo $normalized['LastName'];
If you are not sure where the lastname lives, you could write a function to do this like this ...
function getValue($mykey, $myarray) {
foreach($myarray as $a) {
if($a['name'] == $mykey) {
return $a['value'];
}
}
}
Then you could use
print getValue('LastName', $array);
This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:
`foreach($array as $arr){
(if $arr['name'] == "lastName")
print_r($arr['value']
}`

wordpress $wpdb select results to an array

$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}

How to not echo array if previous one's key has been echoed already

This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));

php - adding values in an array

I'm trying to loop through a multidimensional array, and add a new sub array. My code doesn't return any errors, but it also doesn't add the new item.
I have the following code:
foreach ($data['switches'] as $switch) {
foreach ($switch['atags'] as $attributelist) {
$nohardwareAttribFound = false;
foreach ($attributelist as $attribute) {
$pos = strpos(trim($attribute),'$attr_2_');
if ($pos !==false) {
//echo 'in the loop';
//found it. extract and exit loop
$modelnumber = substr(trim($attribute),8);
$hardwaremodel = array();
$hardwaremodel['tag'] = 'hardware_model:'.$modelnumber;
array_push($switch['atags'],$hardwaremodel);
print_r($switch);
//echo '<br>=====<br>';
$nohardwareAttribFound = true;
}
}//end foreach ($attributelist
}// end foreach ($switch['atags']
if ($nohardwareAttribFound==false) {
$hardwaremodel['tag'] = 'Unknown';
array_push($switch['atags'],$hardwaremodel);
}//end if
}// end foreach ($data['switches']
I would like the data to look like:
[atags] => Array (
[0] => Array ( [tag] => $id_365 )
[1] => Array ( [tag] => $typeid_8 )
[2] => Array ( [tag] => $any_object )
[3] => Array ( [tag] => $casd )
[4] => Array ( [tag] => $unmounted )
[5] => Array ( [tag] => $no_asset_tag )
[6] => Array ( [tag] => $attr_2_1086 )
[7] => Array ( [tag] => $untagged )
[8] => Array ( [tag] => hardware_model:1086 ) ) )
where the last array - element [8], represents a new subarray that I've added. The print_r() statement looks correct, but when I loop through the results that are passed to my view, i can see that in fact, a new tag array has not been added.
Do i need to some sort of a replace instead of the array_push()?
If it's not a good idea to modify an array while looping through it, could I simply check to see if an item exists.
how would i check if the ['atags'] array for each switch contains a [tag] with a value that looks like "$attr_2_NNNN" where N is a number? For example, check out element 6 in the sample array above. The challenge is that it's not always element 6, and you're not always guaranteed that a tag will have the attr_2 value.
I know there is an in_array() function ... i will try something like:
if (in_array(array('$attr_2_'), $switches['atags']))
I have a bug with the logic around the $nohardwareAttribFound variable, which i'm going to fix.
Thanks
First of all: it is not advised to change an array or collection while you are iterating over it.
If you really want to do it like this, then you should take $switch by reference instead of by value. Otherwise you can change $switch to whatever you want, it will not be reflected in the $data['switches'] array.
To take $switch by reference just add the &:
foreach ($data['switches'] as &$switch) {
}
Check out foreach in PHP manual.
EDIT After studying your code, I think this is what you are looking for:
foreach ($data['switches'] as &$switch) {
$hardwaremodel = array();
$hardwaremodel['tag'] = NULL; // initialize to NULL so we can check at the end of the loop if we have found a hardwaremodel or not (so we don't need that bool)
foreach ($switch['atags'] as $attributelist) {
foreach ($attributelist as $attribute) {
$pos = strpos(trim($attribute), '$attr_2_');
if ($pos !== false) {
$modelnumber = substr(trim($attribute), 8);
$hardwaremodel['tag'] = 'hardware_model:' . $modelnumber;
break;
}
}
if ($hardwaremodel['tag'] !== NULL)
break; // exit the loop because we already found a tag
}
if ($hardwaremodel['tag'] === NULL)
$hardwaremodel['tag'] = 'hardware_model:unknown';
// Note that this is a safe place to modify the $switch array
// as we are not currently iterating it
array_push($switch['atags'], $hardwaremodel);
}
Everytime you enter the loop your interation variable (ie. $switch) is a copy - youre not modifying the original array $data. To do that you need to modify the full path like:
array_push($data['switches']['atags'], $newVal)
Or you can pass by reference when you enter the loop like:
foreach ($data['switches'] as &$switch)
{
// ...
}
I think you should replace
foreach ($data['switches'] as $switch)
with
foreach ($data['switches'] as &$switch)
Using a reference should do.
Note: use unset($switch) afterwards to destroy the reference.

Echo a multidimensional array in PHP

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.
In the case of the array below, the right order to echo would be:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
This is the array I was talking about:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)
<pre>
<?php print_r ($array); ?>
</pre>
It looks like you're only trying to write one important value from each array. Try a recursive function like so:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).
Proper, Better, and Clean Solution:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
You simply call in this helper function traverseArray($array) in your current/main class like this:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/
print_r($arr) usually gives pretty readable result.
if you wanted to store it as a variable you could do:
recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
$array_text = recurse_array($array);
Obviously you can format as needed!
There are multiple ways to do that
1) - print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
//-------------------------------------------------
2) - use var_dump($array) to get more information of the content in the array like datatype and length.
//-------------------------------------------------
3) - you can loop the array using php's foreach(); and get the desired output.
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}
Try to use var_dump function.
If you're outputting the data for debugging and development purposes, Krumo is great for producing easily readable output. Check out the example output.
Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

Categories