I have this code right now, it fetches the date and time. I wanted to create kind of a numbered index because I get back about 10 date and times in that one foreach loop. It's in a function and I need to return this array to do something with it elsewhere.
$i = 0;
foreach ($data as $key =>$value) {
$new_data = array (
$i => array (
"date"=> $value->DATE,
"time"=> $value->TIME,
)
);
$i++;
}
I wanted it to look more like this
Array (
[0] => Array (
[date] => whatever date
[time] => whatever time
)
[1] => Array (
[date] => whatever date
[time] => whatever time
)
[2] .. etc
)
Turns out that's not what I'm getting. I get this.
Array (
[10] => Array (
[date] => whatever date
[time] => whatever time
)
It only prints out in one / just gives me the tenth. How would I get it to keep ++ing the $i variable to allow me to get it in the numbered indices? Why is it only showing me the tenth?
You probably wanted just this:
$new_data = array();
foreach ($data as $value) {
$new_data[] = array (
"date"=> $value->DATE;
"time" => $value->TIME;
);
}
First, without [], you just assign a new value to $new_data variable at each iteration. With it, you append a new element to an array at each step; that's obviously what should be done in this case.
Second, you don't have to use another variable in this case: indexing starts from 0, and with each new [] increases as it should be.
Finally (kudos to #reformed for mentioning that in comments), you don't have to write long form of foreach if you actually don't use array's keys. foreach $arr as $val is sufficient.
In my opinion, that may be rewritten more concise with array_map:
$new_data = array_map(function($val) { return array(
'date' => $val->DATE,
'time' => $val->TIME
); }, $data);
This function usually is quite a fit when one wants to create a normal array based on another array, and each element of this new array is somehow based on the corresponding element of the original collection.
I've used an anonymous function here as an argument of array_map, that's available since PHP 5.3.
$i = 0;
foreach ($data as $key =>$value) {
$new_data[$i++] = array (
"date"=> $value->DATE;
"time" => $value->TIME;
)
);
}
Related
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'];
}
}
I have the following code, as you can see I would like to create a new array inside the foreach. Even though its adding perfectly fine WITHIN the loop , all seems to be forgotten once the loop is finished.
foreach ($results as $result) {
$result['categories'] = array();
echo '<pre>';print_r($result);echo '</pre>';
}
echo '<pre>';print_r($results);echo '</pre>';
Result of first print_r
Array
(
[word_two_id] => 2
[categories] => Array
(
)
)
Array
(
[word_two_id] => 3
[categories] => Array
(
)
)
Array
(
[word_two_id] => 5
[categories] => Array
(
)
)
Array
(
[word_two_id] => 12
[categories] => Array
(
)
)
Result of second print_r
Array
(
[0] => Array
(
[word_two_id] => 2
)
[1] => Array
(
[word_two_id] => 3
)
[2] => Array
(
[word_two_id] => 5
)
[3] => Array
(
[word_two_id] => 12
)
)
$result in the foreach is going to be overwritten in your loop on every iteration. e.g. every time the loop rolls around, a NEW $result is created, destroying any modifications you'd done in the previous iteration.
You need to refer to the original array instead:
foreach ($results as $key => $result) {
^^^^^^^
$results[$key]['categories'] = array();
^^^^^^^
Note the modifications. You may be tempted to use something like
foreach($results as &$result)
^---
which would have worked, but also leave $result a reference pointing somewhere inside your $results array. Re-using $result for other purposes later on in the code would then be fiddling with your array, leading to very-hard-to-track bugs.
In PHP, the foreach loop operates on a shallow copy of the array, meaning that changes to the elements of the array won't propagate outside of that loop.
To pass the array elements by reference instead of by value, you put an ampersand (&) before the name of the element variable, like so:
foreach ($results as &$result) {
$result['categories'] = array();
echo '<pre>';print_r($result);echo '</pre>';
}
This way, any changes to the array elements are instead performed on a reference to that element in the original array.
Marc B made a good point in his answer regarding a consequence of using this method. After the foreach loop is done and the code continues, the variable $result will continue to exist as a reference to the last element in the array. So, you shouldn't reuse the $result variable without removing its reference first:
unset($result);
You will need the key too
try this
foreach ($results as $key=>$result) {
$result['categories'] = array();
$results[$key] = $result;
}
echo '<pre>';print_r($results);echo '</pre>';
Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.
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"];
}
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;
}