Foreach loop through an array of JSON from an API - php

I'm creating a stock market portfolio website with the use of the IEX API but I'm currently stuck on one part when it comes to retrieving data as an array and then storing the values in a table.
Here's the code:
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=F,AAPL&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value)
echo '<br/>'. $divi.' : '. $value;
var_dump($div);
What I'm getting now is this:
Notice: Array to string conversion in
E:\XAMPP\htdocs\website2\test.php on line 34
F : Array
Notice: Array to string conversion in
E:\XAMPP\htdocs\website2\test.php on line 34
AAPL : Array
From the var_dump, I get this:
array(2) { ["F"]=> array(1) { ["stats"]=> array(1) {
["dividendRate"]=> float(0.13) } } ["AAPL"]=> array(1) { ["stats"]=>
array(1) { ["dividendRate"]=> float(2.52) } } }
And essentially, I want to have the dividend amount displayed instead of the word 'array', next to the symbols, in a table- what am I missing here?
Thanks!

You need to further reference the right array elements to get this value in your loop...
foreach($div as $divi => $value) {
echo '<br/>'. $divi.' : '. $value['stats']['dividendRate'];
}

As you can see from the var_dump, this data is an array of arrays of arrays. When you try to echo an array, it will only output the string 'Array'. Specify the keys of the elements of that array to get to the actual data.
foreach($div as $divi => $value) {
echo $divi . ':' . $value['stats']['dividendRate'];
}
This is data formatted.
array(2) {
["F"]=> array(1) {
["stats"]=> array(1) {
["dividendRate"]=> float(0.13)
}
}
["AAPL"]=> array(1) {
["stats"]=> array(1) {
["dividendRate"]=> float(2.52)
}
}
}

Related

Remove duplicates from PHP which has multiple arrays [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
This is the current output I have from an array by doing var_dump($getvals):
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
What I want to achieve is first of all, to ignore the ['label'] tables and then try removing any duplicates (150mm and 125mm). I have tried both array_unique and !inarray() but it won't work. Here is my code:
$getvals = get_sub_field('option_diameter'); // This is my array
$takens = array(); // I create an empty array for later on
foreach ($getvals as $key => $getval){ // Running through the array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($getval, $takens)){ // Check if the current value is already inside $takens array
$takens[] = $getval; // If not, then put it
}
}
}
var_dump($takens); // The output is below
This is what I get from var_dump($takens) :
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "125mm"
}
array(1) {
[0]=>string(5) "125mm"
}
The duplicate values are not removed. Any ideas?
Use a key to remove the duplicate, Demo
$result = [];
foreach($array as $arr){
$result[$arr['value']] = $arr;
}
print_r(array_values($result));
You need to first fetch value by using array_diff_key. Then you need to use array_column, in which passing null as second parameter and unique by value as key to removing duplicates(as keys can not be duplicated). Then to reset indexes array_values
Here is the script,
$takens = array_values(array_column(array_map(function ($a) {
return array_diff_key($a, ['label' => '']);
}, $getvals), null, 'value'));
Demo
Output:-
array(2) {
[0]=>
array(1) {
["value"]=>
string(5) "150mm"
}
[1]=>
array(1) {
["value"]=>
string(5) "125mm"
}
}
You can use array_column
$r = array_values(array_column($a, null, 'label'));
OR
if you want to keep single column
$r = array_values(array_column($a, 'value', 'label'));
print_r($r);
array_values will reorder the keys of the array
Working example :- https://3v4l.org/n8SA1
It look like you forgot a foreach.
Here a test done a few minutes ago :
$aArrayTest = array (
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
)
);
$aArrayResult = array();
foreach ($aArrayTest as $aArray) { // Running through the array of Arrays
foreach ($aArray as $key => $value){ // Running through each array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($value, $aArrayResult)){ // Check if the current value is already inside $takens array
$aArrayResult[] = $value; // If not, then put it
}
}
}
}
var_dump($aArrayResult);</pre>

PHP Change multidimensional array structure

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);

Create a n.2 PHP array from JSON output

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
}
}

Unable to iterate on the content of an array

I have an array which contents data that I can see on doing a var_dump() but I am unable to iterate through its content using foreach()
The var_dump() generates the following output
array(4) { [0]=> array(1) { [0]=> string(5) "Admin" } [1]=> array(1) { [0]=> string(4) "rick" } [2]=> array(1) { [0]=> string(6) "techbr" } [3]=> array(1) { [0]=> string(7) "testdom" } }
I want to be able to get the content of this array and store it in another.
Currently I am using the following code
$empList = array();
$empList = emp_list($mysqli);
var_dump($empList);//This generated the above output
foreach ($empList as $value)
{
echo $value."<br>";
}
Output of the echo is this
Array
Array
Array
Array
How do I sort this out?
Thank you for your suggestions I have modified the code this way
$i=0;
$empList = array();
$tempList = array();
$tempList = emp_list($mysqli);
foreach ($tempList as $value)
{
$empList[$i] = $value[0];
$i++;
}
Now the $empList array stores stuff in the correct format
It has an array inside another array so, use two foreach loops
$empList = array();
$empList = emp_list($mysqli);
foreach ($empList as $value)
{
foreach ($value as $temp)
{
echo $temp."<br>";
}
}
As u_mulder says in the comments on your question, your array isn't an array of strings - it's an array of more arrays. var_dump() is designed to deal with complicated nested contents, but echo can't print arrays - that's why it's just telling you that each item in $empList is an array, and not what its contents are.
If you wanted to get the content out of a specific array in $empList you'd need to access it by its index key, with something like:
$first = $empList[0];
foreach ($first as $value) {
echo $value."<br>";
}
Or if you wanted to iterate through them all you could just put two foreach loops one inside the other.

Foreach loop working, but outputting "invalid argument"?

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"
}
}
}
}
}

Categories