Array
(
[menu-162] => Array
(
[attributes] => Array
(
[title] => example1
)
[href] => node/13
[title] => test1
)
[menu-219] => Array
(
[attributes] => Array
(
[title] => example2
)
[href] => node/30
[title] => test2
)
)
If I assign the above array to a variable named $hello, now, I want to use a loop only output the menu-162, menu-219.
If I want to only output the attributes title value, if I only want to output the href's value.
How do I write these loops?
foreach ($hello as $item) {
$attr = $item['attributes']['title'];
$href = $item['href'];
echo "attr is {$attr}";
echo "href is {$href}";
}
That should output the attr and href.
You can access titles value within the attributes array like so: $hello['menu-162']['attributes']['title'] and for any other 'menu' you can substitute menu-162 with the appropriate menu-number combination. As for the href a simple $hello['menu-162']['href']
As for a loop to access both the values a simple foreach should suffice:
foreach($hello as $value) {
echo $value['attributes']['title'];
echo $value['href'];
}
foreach($hello as $key => $value) {
switch($key) {
case 'menu-162':
case 'menu-219':
if($value['href'] && $value['attribute'] && $value['attribute']['title']) {
$href = $value['href'];
$attr = $value['attribute']['title'];
}
break;
default:
continue; //didn't find it
break;
}
}
If you do not need the specific menu finding, remove the switch statement. If you do need the specific ids using this is the more scalable solution, and is faster than a nested if. It will also not create notices for variables that don't exist and will only return if both attribute title, and href exist.
Related
I am trying to get a specific value from a JSON response and am having trouble figuring out how to target it. I can loop through it but I want to only output a single value based on the key as the response is dynamic and not always guaranteed to have the same output.
I have converted the JSON response to an array and here is an example of what I have at this point:
Array (
[0] => Array (
[rel] => advertisements
[href] => https://api.teamsnap.com/v3/advertisements
)
[1] => Array (
[rel] => active_season_team
[href] => https://api.teamsnap.com/v3/teams
)
[2] => Array (
[rel] => assignments
[href] => https://api.teamsnap.com/v3/assignments
)
[3] => Array (
[rel] => availabilities
[href] => https://api.teamsnap.com/v3/availabilities
)
)
I need to be able to echo the "href" value by the key "rel". I have tried:
foreach($links as $key => $value) {
echo $key['advertisements'];
}
But need a way to say $links as $key->rel = $value->http (thats the logic I can come up with)
You can use array_search on the rel column (extracted using array_column) to find the key of a matching value (e.g. advertisements). If it exists, you can then access the value directly:
if(($key = array_search('advertisements', array_column($links, 'rel'))) !== false) {
echo $links[$key]['href'];
}
Output
https://api.teamsnap.com/v3/advertisements
Demo on 3v4l.org
For more flexibility, you could write this as a function:
function get_link($links, $cat) {
if(($key = array_search($cat, array_column($links, 'rel'))) !== false) {
return $links[$key]['href'];
}
else {
return '';
}
}
echo get_link($links, 'active_season_team');
Output:
https://api.teamsnap.com/v3/teams
Demo on 3v4l.org
I didn't understand your requirements but as per syntax, In your case key will be index of array you can get data as below:
foreach($links as $link){
echo $link['rel'].' = '.$link['href'];
}
supposing I have an array like the one below:
Array
(
[0] => Array
(
[id] => 1
[title] => Group1
[description] => This is the group1.
)
[1] => Array
(
[id] => 2
[title] => Group2
[description] => This is group2.
)
)
Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?
Thanks for any help.
Try this :
$title = "Group2";
foreach($your_array as $val){
if($val['title'] == $title){
echo $val['description'];
break; //cut back on unnecessary looping
}
}
Try like this
foreach($myarray as $val){
if($val['title'] == "Group2"){
echo 'This is description '.$val['description'];
}
}
You'll have to iterate over the main array and scan it for that title.
Assuming your main array is called $groups :
$title = 'Group2';
foreach($groups as $key => $group){
if ($group['title'] == $title){
$groupDescription = $group['description'];
// if you need to reference this group again, save it's key.
$groupKey = $key;
}
}
You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.
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.
I have an array that I need to add some key/value pairs too but I'm having trouble with it. Here's an example of my array:
Array
(
[0] => Array
(
[id] => 108
[pagetitle] => Title
[description] =>
[parent] => 35
[alias] => url-alias
[menutitle] =>
)
)
I'm trying to insert a new key called "country" along with it's value but I can't figure out what I'm doing wrong.
foreach($all_items as $item) {
$country = $modx->getTemplateVarOutput(array("country"), $item['id'], $published=1);
$item['country'] = $country['country'];
}
I've verified that $country['country'] does contain what I need it to...I just can't seem to add it to the array.
You need to pass array element by reference if you want to modify it.
foreach($all_items as &$item) {
...
That is because the $item array is actually only a copy of the the element within $all_items.
To achieve what you want you could do it like this:
foreach($all_items as &$item) {
$country = $modx->getTemplateVarOutput(array("country"), $item['id'], $published=1);
$item['country'] = $country['country'];
}
Also see docs for foreach there you'll find exactly that.
This should do what you are asking:
foreach($all_items as $k=>$v) {
$country = $modx->getTemplateVarOutput(array("country"), $all_items[$k]['id'], $published=1);
$all_items[$k]['country'] = $country['country'];
}
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/