Search multidimensional arrays for specific keys and output their data - php

I have following array construction: $array[$certain_key][some_text_value]
And in a while loop, I want to print the data from the array, where $certain_key is a specific value.
I know how to loop through multidimensional arrays, which is not the complete solution to this problem:
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
I do not want to loop the whole array each time, but only when $certain_key is matched.
EDIT: to be more exact, this is what I'm trying to do:
$array[$array_key][some_text];
while reading from db {
//print array where a value returned from the db = $array_key
}

while ($row = fetch()) {
if (isset($array[$row['db_id']])) {
foreach ($array[$row['db_id']] as $some_text_value => $some_text_values_value) {
echo ...
}
}
}

foreach ($array as $certain_key => $value) {
if($certain_key == $row['db_id']) {
foreach ($value as $some_text_value) {
echo "$v2\n";
}
}
}

You mean like
foreach($array[$certain_key] as $k => $v)
{
do_stuff();
}
?

Maybe you're looking for array_key_exists? It works like this:
if(array_key_exists($certain_key, $array)) {
// do something
}

<?php
foreach ($a as $idx => $value) {
// replace [search_value] with whatever key you are looking for
if ('[search_value]' == $idx) {
// the key you are looking for is stored as $idx
// the row you are looking for is stored as $value
}
}

Related

PHP search multidimensional array with more than one result?

I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.
My array looks like this (the first layer of keys goes from 0, 1, 2 etc):
Array
(
[0] => Array
(
[mydevice] => blahblah
[ipadd] => 10.10.10.209
[portnum] => 16040
)
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
$myoutput = searcharray($ptn2, mydevice, $newresult);
I can then echo the results using something like $newresult[$myoutput][mydevice].
However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).
That is because return breaks the function. You could use something like this:
function searcharray($value, $key, $array) {
$result = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$result[] = $k;
}
}
return $result;
}
Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.
$mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
foreach ($mydevicekeys as $mydevicekey) {
// work with $newresult[ $mydevicekey ]["mydevice"]
}
So add the results to an array :)
function searcharray($value, $key, $array) {
$res = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$res[] = $key;
}
}
return $res;
}

How to get index's value from $_POST using foreach

I want to know the correct code to detect only numerical $_POST fields coming from the form.
Please correct my code.
foreach ($_POST as $vals) {
if (is_numeric($vals)) {
if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
//do something
}
}
$_POST = array_filter($_POST, "is_numeric");
The above will remove all non-numeric array items.
foreach (array_filter($_POST, "is_numeric") as $key => $val)
{
// do something
echo "$key is equal to $val which is numeric.";
}
Update:
If you only want those like $_POST[1], $_POST[2], etc..
foreach ($_POST as $key => $vals){
if (is_numeric($key)){
//do something
}
}
try:
foreach ($_POST as $key => $vals){
//this is read: $_POST[$key]=$value
if (is_numeric($vals) && ($vals!="0")){
//do something
}
}
if(isset($_POST)){
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
}
Compare the keys
Try this:
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
The following code with isset() trying to work on an array is invalid.
if(isset($_POST)){ //isset() only works on variables and array elements.
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
Better, but now foreach will make a copy of $_POST and put in in memory for the duration of the loop (Programming PHP: Ch. 6, p. 128-129). I hope buffer overflows or out of memory errors don't jump up and bite you. :-)
Perhaps it would be wiser to determine some facts about $_POST with is_array(), empty(), count() and others before getting started, such as ...
if(is_array($_POST) && !empty($_POST))
{
if(count($_POST) === count($arrayOfExpectedControlNames))
{
//Where the the values for the $postKeys have already been validated some...
if(in_array($arrayOfExpectedControlNames, $postKeys))
{
foreach ($_POST as $key => $val) //If you insist on using foreach.
{
if (is_numeric($key))
{
// do something
}
else
{
//Alright, already. Enough!
}
}
}
else
{
//Someone is pulling your leg!
}
}
else
{
//Definitely a sham!
}
}
else
{
//It's a sham!
}
Still, the $val values need some validation, but I'm sure you are up on that.

How to foreach through part of an objects member variables that are arrays?

I am trying to create a foreach that will go through some variables within an object.
At the moment it is just
class jabroni
{
var $name = "The Rock";
var $phrases = array ("The rock says", "Im gonna put the smackdown on you", "Bring it on jabroni");
var $moves = array ("Clothes line", "Pile driver", "Reverse flip");
}
I tried doing this:
$jabroni = new jabroni()
foreach ($jabroni as $value)
{
echo $value->phrases;
echo $value->moves;
}
However nothing gets printed.
Any ideas if what I am trying to achieve is possible, I have that gut feeling that its not and that I will have to just do individual foreach statements for each object member variable that is an area?
Thanks for your time!
You are doing wrong the loop.. You have one object, not an array of objects. so the correct way should be..
$jabroni = new jabroni();
foreach ($jabroni->phrases as $value)
{
echo $value;
}
foreach ($jabroni->moves as $value)
{
echo $value;
}
foreach ($jabroni->phrases as $value) {
echo $value;
}
foreach ($jabroni->moves as $value) {
echo $value;
}
You can do it in nested foreach loops. This will be easy instead of going for two for loops seperatley
foreach ($jabroni as $keys => $values)
{
if ($keys == 'phrases' || $keys == 'moves') {
foreach ($values as $value) {
echo $value;
}
}
}

Anything to attend when changing values in a multidimensional foreach() loop?

I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?
foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.
You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.

How to delete object from array inside foreach loop?

I iterate through an array of objects and want to delete one of the objects based on it's 'id' property, but my code doesn't work.
foreach($array as $element) {
foreach($element as $key => $value) {
if($key == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($element);//this doesn't work
unset($array,$element);//neither does this
}
}
}
Any suggestions. Thanks.
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
Be careful with the main answer.
with
[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']
and calling the function
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'cat' && $value == 'vip'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
it returns
[2=>['id'=>3,'cat'=>'normal']
instead of
[0=>['id'=>3,'cat'=>'normal']
It is because unset does not re-index the array.
It reindexes. (if we need it)
$result=[];
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
$found=false;
if($valueKey === 'cat' && $value === 'vip'){
$found=true;
$break;
}
if(!$found) {
$result[]=$element;
}
}
}
It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.
The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.
This should do the trick.....
reset($array);
while (list($elementKey, $element) = each($array)) {
while (list($key, $value2) = each($element)) {
if($key == 'id' && $value == 'searched_value') {
unset($array[$elementKey]);
}
}
}
You can also use references on foreach values:
foreach($array as $elementKey => &$element) {
// $element is the same than &$array[$elementKey]
if (isset($element['id']) and $element['id'] == 'searched_value') {
unset($element);
}
}
I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

Categories