Trouble Adding New Item to Array - php

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'];
}

Related

Pull out values from multidimensional associative array

I have a multidimensional array which Im trying to pull all the values of a certain key and assign it to a variable.
This is the array:
Array
(
[I_would_not_know_the_name_of_this_key] => Array
(
[interval] => 3600
[display] => Once Hourly
)
[nor_this_one] => Array
(
[interval] => 43200
[display] => Twice Daily
)
[nor_this_one] => Array
(
[interval] => 86400
[display] => Once Daily
)
)
I want to always get the [display] value even when I do not know what the upper level value is.
function which contains the array above, more schedules can be added which is why I said I would not always know the top level key: https://codex.wordpress.org/Function_Reference/wp_get_schedules
My code so far:
$active_cron_schedules = wp_get_schedules(); //this is the
foreach ($active_cron_schedules as $key => $value) {
echo $key;
}
?>
This outputs for example: 'I_would_not_know_the_name_of_this_key', 'nor_this_one', 'nor_this_one', I need to get in deeper.
Arrays have always given me a run for my money in PHP can't figure out how to loop through it :(
Thank you
I think what you are trying to do will be solved with a foreach() loop or array_column() depending on your version of php. The variable part is hard to answer because you have not given an example of what you would be doing with the variable. A common mistake is to overwrite the variable in a loop, but if all you want are all the display values (or any other key), try:
function getValByKey($array, $getKey = 'display')
{
$new = array();
foreach($array as $arr) {
if(empty($arr[$getKey]))
continue;
$new[] = $arr[$getKey];
}
return $new;
}
$result = array(
'key1'=> array('interval'=>1,'display'=>'1d'),
'key2'=> array('interval'=>2,'display'=>'2d'),
'key3'=> array('interval'=>3,'display'=>'3d')
);
// To use
$display = getValByKey($result);
print_r($display);
// Array column has the same basic function, but
// Only available in PHP 5 >= 5.5.0, PHP 7
$display = array_column($result,'display');
print_r($display);
Both give you:
Array
(
[0] => 1d
[1] => 2d
[2] => 3d
)
whatever is the key, you dont even need to know it in a foreach.
here is a sample. $key can be anything. you just have to check for it s interval child element.
$interval_list = array();
foreach ($array as $key => $el) {
if (isset($el['interval'])) {
$interval_list[] = $el['interval'];
}
}

Access corresponding value in PHP array given a certain known value

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.

PHP remove nested arrays

I have an array $templates that looks like this:
Array
(
[0] => Array
(
[displayName] => First Template
[fileName] => path_to_first_template
)
[1] => Array
(
[displayName] => Second Template
[fileName] => path_to_second_template
)
[2] => Array
(
[displayName] => Third template
[fileName] => path_to_third_template
)
)
And I want to make it to look like this:
Array
(
[path_to_first_template] => First Template
[path_to_second_template] => Second Template
[path_to_third_template] => Third Template
)
That is, I want the fileName of the nested arrays to be the new array's key and displayName to be its value.
Is there a pretty way to do this without having to loop through the array. I had no luck searching, as I didn't know exactly what to search for.
Here's a classic foreach in action:
$result = array();
foreach($array as $row) {
$result[$row['fileName']] = $row['displayName'];
};
Here's a "clever" way to do it:
$result = array();
array_walk($array, function($row) use (&$result) {
$result[$row['fileName']] = $row['displayName'];
});
As you can see, the second approach is not really better than the first one. The only advantage is that theoretically you can pile upon the second form because it is a single expression, but in practice it's a long enough expression already so you wouldn't want to do that.
Loop in your array and make a new one:
$newArray = array();
foreach($array as $val){
$newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);
$ret = array()
foreach ($templates as $template) {
$ret[$template["fileName"]] = $template["displayName"];
}

Building array from other arrays

I am trying to build a new array from simpleXmlElement. I am getting the information I want, just not in the right hierarchy.
$xmlNew1 = new SimpleXMLElement($responseNew1);
$test = array();
foreach ($xmlNew1->children() as $newChild){
$classIden[] = (string)$xmlNew1->class['id'];
$item[] = (string)$xmlNew1->code;
$family[] = (string)$xmlNew1->family;
for($i=0, $count = count($classIden); $i < $count; $i++) {
$test[$item[$i]][$family[$i]]= $classIden[$i];
}
}
print_r($test);
this gives me:
Array
(
[9522] => Array
(
[Mens Hats] => 44
)
[9522-NC-NO SIZE] => Array
(
[Mens Hats] => 44
)
[B287CSQU] => Array
(
[Boys] => 1
)
but I want
Array
(
[9522] => Array
(
[family] => Mens Hats
[classId] => 44
)
Any suggestion? Thanks!
This should probably do it (to replace the main loop contents):
$id = (string)$newChild->class['id'];
$code = (string)$newChild->code;
$family = (string)$newChild->family;
$items[$code] = array(
'family' => $family,
'classId' => $id,
);
Edit
Forgot to use $newChild instead of $xmlNew1.
I don't know your hierarchy because I do not know much about the HTML. You've hidden the structure. However, you should probably build the array in the format you look for directly.
Let us try to make that less complicated. Let's say you have a variable that would contain all the children. So you can pull apart the iteration and loading these children. Loading:
$xmlNew1 = new SimpleXMLElement($responseNew1);
$newChildren = $xmlNew1->children();
I can not say you if $xmlNew1->children() is sufficient to get you all the xml elements you are looking for, but let's just assume so.
Next part is about the iteration. As written you should build the $test array while you iterate over the children - as you partly already did:
$test = array();
foreach ($newChildren as $newChild) {
...
}
Missing part now is to create your structure in $test:
Array(
[9522] => Array(
[family] => Mens Hats
[classId] => 44
)
I like the suggestion #Jack gives here to first assign the values you want to extract to variables of their own and then create the entry.
$newItem = array(
'family' => $family,
'classId' => $id,
);
$test[$code] = $newItem;
Naturally you have to place that into the iteration. When the iteration is done, the $test array should have the format you're looking for.
I hope this is helpful.

Convert PHP array into Key => Value Array

Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}

Categories