I have an array with arrays in it. I need to loop through it so I have both the index as a variable, and the value as one as well.
I have run print_r($array) on my array and this is displayed:
Array
{
[ns] => Array
{
[car1]=>chevy
[car2]=>dodge
}
[mx] =>Array
{
[color1]=>red
}
}
I need the loop to display:
car1 chevy
car2 dodge
color1 red
I know I need a foreach loop but I can not seem to get it to work correctly. I always get the error:
trying to get property of non object
Below you'll find an example how to loop trough keys and values.
<?php
foreach($yourArr as $key => $value){
//$key will contain ns and mx
//$value will contain Array and Array
//So we need to loop through $value
foreach($value as $subKey => $subValue){
//$subKey will contain car1, car2 and color1
//$subValue will contain chevy, dodge, red
}
}
Going through an array of arrays to get the values of the inner arrays works like this:
foreach($array as $row => $subArray)
{
foreach($subArray as $subRow => $value)
{
echo $value . "<br/>";
}
}
Related
So not a stranger to PHP or arrays even, but never had to deal with multidimensional arrays and its doing my head in.
I have the output of a PHP to a server API and need to pull all the mac address values from the (dst_mac) keys, but only on the occasion the category (catname) keys value for each element is emerging-p2p
The format of the array is like this (intermediate keys and values removed for brevity)
[1] => stdClass Object
(
[_id] => 5c8ed5b2b2302604a9b9c78a
[dst_mac] => 78:8a:20:47:60:1d
[srcipGeo] =>
[dstipGeo] => stdClass Object
(
)
[usgipGeo] => stdClass Object
(
)
[catname] => emerging-p2p
)
Any help much appreciated, i know when im out of my depth!
From your example that is an array with a std class. you can use the empty funtion.
//checks if the first key
if (!empty($array[1]->_id)) {
echo $array[1]->dst_mac;
// or do what you want.
}
This example only applies to one array. use a loop to have this dynamically done.
EDIT: My answer was based on your question. Didn't realize you have to check the catname to be 'emerging-p2p' before you get the mac address?
// loop through the array
foreach ($array as $item) {
// checks for the catname
if ($item->catname === 'emerging-p2p') {
// do what you want if the cat name is correct
echo $item->dst_mac;
}
}
Is this what you want?
for($i =0;$i<count($arr);$i++){
if(isset($arr[$i]['catname']) && $arr[$i]['catname']=='emerging-p2p'){
echo $arr[$i]['dst_mac'];
}
}
If there is only one object that has 'emerging-p2p' cat name:
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
return $obj->dst_mac;
}
}
If there are many:
$result = [];
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
$result[]= $obj->dst_mac;
}
}
return $result;
Use for loop.
for($i =0; $i<=count($arr); $i++){
if(arr[$i]['catname']=='emerging-p2p'){
echo arr[$i]['dst_mac'];
}
}
To fetch all the mac where catname is emerging-p2p
//Assuming $arr has array of objects
$result_array = array_filter($arr, function($obj){
if ($obj->catname == 'emerging-p2p') {
return true;
}
return false;
});
foreach ($result_array as $value) {
echo $value->dst_mac;
}
You can use array_column if you need only mac address on the basis of catname.
$arr = json_decode(json_encode($arr),true); // to cast it as array
$temp = array_column($arr, 'dst_mac', 'catname');
echo $temp['emerging-p2p'];
Working demo.
is there a way to loop through an array and unset any variables that are =""?
i am looking for a faster way to do this aside form writing 4 if else statements.i thought this might work but i don't know if it can be done this way or not.
$a=""
$b="123"
$c=""
$d"123"
$var=array($a,$b,$c,$d)
i am trying to loop through $var array to get
$var= array($b,$d)
is this even possible or should i stick with writing 4 if else statements?
Have a look here : How to delete object from array inside foreach loop?
or here :
How do you remove an array element in a foreach loop?
foreach ($array as $key => $value) {
if($value == "") {
unset($array[$key]);
}
}
Good luck
$x=["","123","","345"];
$var = array_filter($x);
print_r($var);
The result:
Array
(
[1] => 123
[3] => 345
)
I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}
Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}
I have an array from which I need to remove null values:
[227] => Array
(
[0] => 3
[1] => 8
[2] =>
[3] =>
[4] => 1
)
)
I tried array_filter($quantity);
and also
foreach ($quantity as $key => $value) {
if (is_null($value) || $value=="") {
unset($quantity);
}
}
and even tried the foreach with $quantity[0] and got Undefined offset 0. Any ideas?
UPDATE
This works but what if i dont have the 227
foreach ($quantityval[227] as $key => $value) {
if (is_null($value) || trim($value)=="") {
unset($quantityval[227][$key]);
}
}
This looks like a nested array -- your foreach statement looks correct, but needs to check the inner arrays:
foreach ($quantity as $key => $item)
foreach ($item as $key2 => $item2) {
if (is_null($item2) || $item2=="") {
unset($quantity[$key][$key2]);
}
}
}
You appear to have values that are all white-space -- either regular spaces or possibly unicode characters. Try trim($value) == "".
If that doesn't work array_filter($array, "is_integer"); may do the trick.
You updated solution works. The part about the hardcoded 227 is because $quantity is a multi-dimensional array (the extra closing parenthesis hinted that too). You need to do nested foreach for that.
foreach($bigArray as $bigKey => $smallArray)
{
foreach($smallArray as $smallKey => $value)
{
if(is_null($value) || $value == "")
unset($bigArray[$bigKey][$smallKey]);
}
}
I use something like this for situations like that:
<?php
function filter_empty_recursive($arr)
{
$keys = array_keys($arr);
foreach($keys as $key)
{
if(is_array($arr[$key]))
{
$arr[$key] = filter_empty_recursive($arr[$key]);
}
else if(empty($arr[$key]))
{
unset($arr[$key]);
}
}
return $arr;
}
It's a recursive function (so it can be a little brutal on memory with large nested array trees, and this particular one cannot handle infinite recursion (i.e.: circular reference).) But with a non-infinite recursion, and reasonably sized nested array trees, it should work pretty well. It can also be expanded to handle nested object properties as well, but that seemed outside scope. The part where it decides if it's empty is that if(empty()) so you can change that back to that is_null or empty string block.
(Edit: Adding really Low level explanation: loops through the array, if it finds an array inside of that array, it calls itself and repeats the process.)