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'];
}
}
Related
Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.
Array
(
[0] => Array
(
[datas] => Array
(
[res] => 1
[rows] => Array
(
[0] => stdClass Object
(
[a] => 11
[b] => 901
[c] => 2
[d] => 2
[e] => A
[f] => BT
[g] => arushi
[h] => arushi#gmail.com
[i] => 123445
[j] => 12355.jpg
)
)
)
)
[1] => Array
(
[datas] => Array
(
[res] => 1
[rows] => stdClass Object
(
[person_name] => arushi
)
)
)
)
if i get the value in that kind off array how can i get the value of
both partially with different variable m not able to understand the
structure of the array..
need to get the value in table seperatly in different different table with same page how i can get the values
You would need to do a foreach loop. The only problem is that if you want to make it dynamic and grab the data by itself without you telling it what to get. If not it means you would have to know exactly what you need and the structure of your results. But seeing that there is a pattern you can do some checks until you reach rows. For example ($array would be the variable that has the data you provided):
foreach ($array AS $arr) {
// To make you function/check work faster,
// before even entering to fetch for data
// you can check if it has any data, else you
// probably will end up with an error
if (isset ($arr ['datas']) && $arr ['datas']) {
foreach ($arr ['datas'] AS $data) {
if (isset ($arr ['res']) && 0 < $arr ['res']) {
// here is where it gets tricky because
// from you example its either an array or an object
// but the kool part about it is that you can convert an object into an array
// or just leave it as is because the foreach will take care of it either way :)
// first check it it is an object and convert if yes
$row = $arr ['rows'];
if (!is_array ($row))
$row = (array)$row; // converting it to array is super easy :)
foreach ($row AS $key=>$dat) {
// from here your result can either be another array or just data
// so you run the check once more
if (is_array ($dat)) {
foreach ($dat AS $k=>$d) {
echo "data for $k is $d";
}
}
else
echo "data for $key is $dat";
}
}
}
}
}
You can use foreach to loop through the arrays which have keys starting from 0 to n. So that you can foreach through the main array to get the datas array for all the keys. For getting rows childs you can use another foreach inside it to get each items. But for rows it is object , so you have to use -> to select the key. see below example code. But on your array the second array consist different formate in rows array. so make it like a common formate to loop through it easily.
For eg :-
foeach($parent_array as $array){
$data=$array['datas'];
$res = $data['res'];
$rows=$data['rows'];
foreach($rows as $row){
echo $row->a; // to get the value of key a = 11
}
}
As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand
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 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;
)
);
}