I'm using
$data=json_decode($response,true)
the output is
array(3)
{
["instrument"]=> string(7) "EUR_USD" ["granularity"]=> string(1) "D" ["candles"]=> array(10)
{
[0]=> array(7)
{
["time"]=> string(27) "2016-09-26T21:00:00.000000Z" ["openMid"]=> float(1.125495) ["highMid"]=> float(1.1259) ["lowMid"]=> float(1.119125) ["closeMid"]=> float(1.121605) ["volume"]=> int(17059) ["complete"]=> bool(true)
}
[1]=> array(7)
{
["time"]=> string(27) "2016-09-27T21:00:00.000000Z" ["openMid"]=> float(1.1218) ["highMid"]=> float(1.12369) ["lowMid"]=> float(1.118215) ["closeMid"]=> float(1.12171) ["volume"]=> int(17915) ["complete"]=> bool(true)
}
}
}
I want to create two arrays with the values openMid and closeMid for example:
$open=array(1.125495,1.1218)
$close=array(1.121655,1.12171)
I have to develop the foreach code in order to achieve that.
Anyone can help me? Thanks
Check out the solution below:
$open= []; //Declare empty array to hold openMid values
$close= []; //Declare empty array to hold closeMid values
#Loop through $array
foreach ($array as $key => $value) {
#If any of the value is an array
if (is_array($value)) {
$arr= $value; //Store the array
}
}
//Loop through the second array
foreach ($arr as $val) {
//If the value is of index openMid
if ($val->openMid) {
$open[]= $val->openMid; //Push into the $open array holder
}
//If the value is of index closeMid
if ($val->closeMid) {
$close[]= $val->closeMid; //Push into the $close array holder
}
}
Related
I'm looping through a multidimensional array of field groups and sub fields Using this code:
<?php
$field_groups = acf_get_field_groups();
foreach( $field_groups as $field_group ) {
$acf_groups = acf_get_fields_by_id( $field_group['ID'] );
foreach($acf_groups as $group) {
echo '<pre>';
var_dump($group);
echo '</pre>';
}
}
Which gets me this array:
array(20) {
["group"]=>
string(6) "button"
["sub_fields"]=>
array(5) {
[0]=>
array(23) {
["name"]=>
string(11) "button_text"
}
[1]=>
array(19) {
["name"]=>
string(11) "button_link"
}
}
}
array(20) {
["group"]=>
string(2) "h1"
["sub_fields"]=>
array(8) {
[0]=>
array(23) {
["name"]=>
string(9) "font_size"
}
[1]=>
array(26) {
["name"]=>
string(15) "font_size_units"
}
}
}
What I'm trying to do is print out a file with the sub_field values for each of the $group arrays ('button' and 'h1' respectively).
So for example, I want to end up with in this case 2 files:
button.php
h1.php
button.php would have:
button_text
button_link
h1.php would have:
font_size
font_size_units
I can get the two files to print out within that loop however the h1.php file includes the button sub_fields values, so:
button_text
button_link
font_size
font_size_units
How can I split the files up by the parent array and then print out a file for each group with its respective sub_fields values?
Figured it out...needed an additional grouped array to group the elements by the key in the nested array, in my case $sub['label'].
This isn't pretty or the most elegant but it works.
<?php
$field_groups = acf_get_field_groups();
foreach( $field_groups as $field_group ) {
$acf_groups = acf_get_fields_by_id( $field_group['ID'] );
$grouped = array();
foreach ($acf_groups as $group) {
$subs = $group['sub_fields'];
foreach($subs as $sub) {
$grouped[$group['label']][] = $sub['label'];
}
foreach ($grouped as $key => $items) {
// print by group here.
}
}
}
I have a long multidimensional array with timestamps as keys which contain arrays of values. Something like this but with more timestamps:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502611200]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(200)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(150)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
How can I remove every every second array of the array without losing the keys as timestamp? So I end up with this:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
If I use a for loop and unset every second key I lose all the keys and end up with 0, 1, 2 etc. instead of the timestamp.
In a loop, check for index and unset every second element:
You can use custom $index variable, like this:
$index = 0; // points to first element
foreach ($array as $key => $value) {
if ($index % 2 != 0) { //check for un-even
unset($array[$key]);
}
$index++; // move pointer to next element
}
$i=1 // where the key to remove
$x=0; //loop to determine the key position
foreach ($array as $key=>$value){
if($x==$i){
unset($array[$key]);
}
$x++;
}
In that kind of case, a simple foreach can be more efficient perfwise than a standard function :
foreach ($array as $key => $val) {
if (array_key_exists('Item2', $val)) {
unset($val['Item2']);
}
}
Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);
Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}
I hope to give enough information here, but I am confused as to why the foreach loop works, it gets each data and outputs it in an li but I am getting an invalid argument error?
Here is the result of the var_dump
array(1) { ["questions"]=>
array(2) { ["title"]=> string(5) "Keanu" [1]=>
array(1) { ["questionlist"]=> array(2) { [0]=>
array(1) {
["a-question"]=> string(1) "1" } [1]=> array(1) {
["a-question"]=> string(5) "civil" } } } } }
Here is my foreach statement
foreach($questions['questions'] as $key => $value){
foreach($value['questionlist'] as $key => $subquestion){ //line 119
echo '<li>'.$subquestion['a-question'].'</li>';
}
}
$questions is a variable used to get the data from the database like this.
$questions = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1" , ARRAY_A);
The data comes from ajax, I modify the ajax $_POST like this before sending to the database.
// Add modifications
$questions['questions'] = $_POST['questions']['data'];
// DB data
$name = $wpdb->escape($questions['questions']['title']);
$data = $wpdb->escape(json_encode($questions));
Screenshot:
I am not sure why I am getting the invalid argument, I suspect its because the array may not be formatted properly, if you need any more information let me know.
A Solution: Thanks to #didierc
I used his code and modified it a bit to display my data in a loop, basically all I did was add another foreach.
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
// This loops all the ['a-question'] data
echo '<li>''.$value['a-question'].''</li>';
}
}
}
}
Try this:
foreach ($questions['questions'] as $key => $value) {
if (is_array($value) && isset($value[ 'questionlist'])) {
foreach ($value['questionlist'] as $subnum => $subquestion) {
foreach ($subquestion as $qtitle => $qanswer) {
With variable names hopefully explicit enough. That should get you started.
NB: The data is probably easier to understand when formatted as below:
array(1) {
["questions"]=> array(2) {
["title"] => string(5) "Keanu"
[1] => array(1) {
["questionlist"]=> array(2) {
[0]=> array(1) {
["a-question"]=> string(1) "1"
}
[1]=> array(1) {
["a-question"]=> string(5) "civil"
}
}
}
}
}