I'm trying to loop through some CSV data and take out the $data[4] item. My eventual goal is to find the average and hopefully use PHP's array_sum. This seems to be working, except that every time I try and create this array, my while loop breaks each value into their own separate arrays ($real), not one array that I can work with. I have tried everything, including working with the arrays outside of the loop, but nothing has worked. Any help would be appreciated!
$symbol=array("XOM","CVX","RDS-A",
"PTR","TOT","SNP","COP",
"IMO","BP","E","STO","EC","SU","MRO");
for($i=0; $i<count($symbol);$i++)
{
$handle = #fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false)
{
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE)
{
$rows++;
$num=count($data);
$real=array($data[4]);
}
var_dump($real);
}
And here's my final output:
array(1) { [0]=> string(9) "92.669998" }
array(1) { [0]=> string(6) "120.00" }
array(1) { [0]=> string(9) "66.290001" }
array(1) { [0]=> string(10) "111.059998" }
array(1) { [0]=> string(5) "58.73" }
array(1) { [0]=> string(9) "82.449997" }
array(1) { [0]=> string(5) "72.82" }
array(1) { [0]=> string(9) "42.740002" }
array(1) { [0]=> string(5) "45.91" }
array(1) { [0]=> string(5) "47.98" }
array(1) { [0]=> string(9) "22.440001" }
array(1) { [0]=> string(5) "41.93" }
array(1) { [0]=> string(5) "34.82" }
array(1) { [0]=> string(5) "35.82" }
Not sure what $context is, but try this...
$symbol=array("XOM","CVX","RDS-A","PTR","TOT","SNP","COP","IMO","BP","E","STO","EC","SU","MRO");
$datas = array();
for($i=0; $i<count($symbol);$i++){
$handle = #fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false){
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE){
$rows++;
$datas[] = $data[4];
}
}
print_r($datas);
Related
My goal is to get specific element/value from a multidimensional array and assign them in a URL in loop. I have already tried and was able to get elements in the array but this displays all elements. I only want to get specific, like nid and field_x values.
This is my link structure: http://localhost:8080/$nid/$field_x
Expected result:
http://localhost:8080/123/one
http://localhost:8080/789/three
This is my sample var_dump result
array(1) {
[0]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(123)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(456)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "One"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Two"
}
}
}
[1]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(789)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(321)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "Three"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Four"
}
}
}
}
You can use a foreach() and get the data using $values['nid'][0]['value'] or $values['field_x'][0]['target_id']:
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
echo "http://localhost:8080/$nid/$field_x" ;
}
Will outputs:
http://localhost:8080/123/One
http://localhost:8080/789/Three
You probably want to do something else than an echo, so you can create a new array:
$urls = [];
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
$urls[] = "http://localhost:8080/$nid/$field_x" ;
}
print_r($urls);
I am calling a REST Api to get data using curl in php. It gives me the list of data/contents in the api in Array php format.
I was able to get single element value using $resultArray[0]['nid'][0]['value'];. But my goal is to get elements in all contents in the api.
Say I want to get the following elements in the nested arrays.
$resultArray[0]['nid'][0]['value'];
$resultArray[0]['vid'][0]['value'];
$resultArray[0]['cid'][0]['value'];
And use these values in a loop too.
I am trying to search how I can do it loop, and if anyone can provide sample code, that would be appreciated.
Update:
This is the sample result of var_dump:
array(1) {
[0]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(1)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(2)
}
}
["cid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(3)
}
}
["field"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
int(4)
}
}
}
[1]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(11)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(22)
}
}
["cid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(33)
}
}
["field"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
int(44)
}
}
}
[2]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(111)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(222)
}
}
["cid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(333)
}
}
["field"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
int(444)
}
}
}
}
And I want to use these elements values in a loop.
Say my expected result is.
Test1 = "1", "2", "3"
Test2 = "11", "22", "33"
Test3 = "111", "222", "333"
These equivalent numbers should be comming from the element nid, vid, cid.
I dont just want to assign/echo these values in the result as I have array[100s] in one api call.
Since your array is a multidimensional array, you need to have nested foreach loops:
$test = 1;
foreach ($resultArray as $items) {
// Echo the current test number
echo "Test{$test} = ";
$values = [];
foreach ($items as $item) {
// Get the correct value.
if (array_key_exists('value', $item[0])) {
$values[] = $item[0]['value'];
continue;
}
if (array_key_exists('target_id', $item[0])) {
$values[] = $item[0]['target_id'];
continue;
}
}
echo '"' . implode('", "', $values) . '"' . "\n";
$test++;
}
Demo: https://3v4l.org/fnHlV
I am trying to execute an SQL query to pull one column of data from my database into a PHP array, and then search for my session variable in that array. I've printed the contents of my array and it looks like the query is working and is filling the array, but my comparison if (in_array("$session", $result)) is not working correctly.
I know the string my session variable contains is inside the PHP array. But $execute never flips to FALSE. Any idea why?
$confirm = $_GET['name'];
$execute = TRUE;
session_start();
$session = $_SESSION['sessionID'];
$result = array();
try{
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(substr($session, 0, 2) === 'DS'){
$sql = $conn->prepare("SELECT confirmNum FROM `DSattendance`");
$sql->execute();
$result = $sql->fetchAll();
}
else if (substr($session, 0, 2) === 'BYOD'){
$sql = $conn->prepare("SELECT confirmNum FROM BYODattendance");
$sql->execute();
$result = $sql->fetchAll();
}
}
catch(PDOException $e){echo $sql . "<br>" . $e->getMessage();}
if (in_array("$session", $result)) {
echo "true";
$execute = FALSE;
}
if ($execute == FALSE)
echo "ALREADY REGISTERED";
var_dump($result) yields:
array(10) {
[0]=> array(2) { ["confirmNum"]=> string(11) "adfafafafaa" [0]=> string(11) "adfafafafaa" }
[1]=> array(2) { ["confirmNum"]=> string(11) "adsfafafaff" [0]=> string(11) "adsfafafaff" }
[2]=> array(2) { ["confirmNum"]=> string(11) "asdfafafafa" [0]=> string(11) "asdfafafafa" }
[3]=> array(2) { ["confirmNum"]=> string(11) "christrader" [0]=> string(11) "christrader" }
[4]=> array(2) { ["confirmNum"]=> string(11) "christradfe" [0]=> string(11) "christradfe" }
[5]=> array(2) { ["confirmNum"]=> string(11) "sadfadfafaf" [0]=> string(11) "sadfadfafaf" }
[6]=> array(2) { ["confirmNum"]=> string(11) "sadfsfafaaf" [0]=> string(11) "sadfsfafaaf" }
[7]=> array(2) { ["confirmNum"]=> string(11) "sdfsafsadfa" [0]=> string(11) "sdfsafsadfa" }
[8]=> array(2) { ["confirmNum"]=> string(11) "trraafafafa" [0]=> string(11) "trraafafafa" }
[9]=> array(2) { ["confirmNum"]=> string(11) "wesdfdfasfa" [0]=> string(11) "wesdfdfasfa" } }
The PDO Statement fetchAll is returning a multi-dimensional array of the results found in the database. You need to loop through them first and format a new array that you can use to check your session against.
foreach($result as $value) {
$array[] = $value['confirmNum'];
}
if( in_array($session, $array)) {
// your code here
}
As noted by #mr12086, depending on the version of PHP you are using, you can avoid the foreach loop by using: $result = array_column('confirmNum', $result); instead. However, this does require PHP 5.5.0 or higher.
I have the following php code that displays csv data on the browser:
$file1 = file('SpreadsheetA.csv',FILE_IGNORE_NEW_LINES);
foreach($file1 as $val)
{
echo $val;
}
the above outputs all the data in the csv file as a string:
Matter Number,Amount,Currency,Company Code100,2000,USD,310101,23000,EUR,110102,120,GBP,120103,10000,USD,310
if i want to capture the above as an array, this is what i do:
foreach($file1 as $val)
{
var_dump(array($val));
}
and this is the output:
array(1) {
[0]=>
string(42) "Matter Number,Amount,Currency,Company Code"
}
array(1) {
[0]=>
string(16) "100,2000,USD,310"
}
array(1) {
[0]=>
string(17) "101,23000,EUR,110"
}
array(1) {
[0]=>
string(15) "102,120,GBP,120"
}
array(1) {
[0]=>
string(17) "103,10000,USD,310"
}
as shown, each string is captured as an array..my wish is to capture all strings under a single array as follows:
array(5) {
[0]=>
string(42) "Matter Number,Amount,Currency,Company Code"
[1]=>
string(16) "100,2000,USD,310"
[2]=>
string(17) "101,23000,EUR,110"
[3]=>
string(15) "102,120,GBP,120"
[4]=>
string(17) "103,10000,USD,310"
}
how would i accomplish the above(inside the foreach loop)??
you should loop your arrays into $file and fill another array with the string values
try this code:
$output = array();
foreach ($file1 as $val) {
$output[] = $val[0];
}
var_dump(array($output));
:) Let's say that i have that code:
<sample number="1">TEXT</sample>
but sometimes it could be
<sample number"1"/>
Q: How to check if it's self closed or not ? Or I want to check if it's there TEXT within element sample
Note: I'm using that way to retrieve XML doc:
$content = #file_get_contents($url);
$xml = new SimpleXMLElement($content);
You need to type cast the element to string, then check if it's empty or not.
Here's a quick example:
$test = simplexml_load_string("<test><elem test='12'><sub /><sub /></elem><elem test='12'>hi</elem><elem test='9' /><elem /></test>");
foreach($test as $elem){
echo "\n";
var_dump($elem);
if((string)$elem == '' && $elem->count() == 0)
echo 'Empty';
else
echo 'Full';
}
Will return:
object(SimpleXMLElement)#3 (2) {
["#attributes"]=>
array(1) {
["test"]=>
string(2) "12"
}
["sub"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#4 (0) {
}
[1]=>
object(SimpleXMLElement)#5 (0) {
}
}
}
Full
object(SimpleXMLElement)#5 (2) {
["#attributes"]=>
array(1) {
["test"]=>
string(2) "12"
}
[0]=>
string(2) "hi"
}
Full
object(SimpleXMLElement)#3 (1) {
["#attributes"]=>
array(1) {
["test"]=>
string(1) "9"
}
}
Empty
object(SimpleXMLElement)#5 (0) {
}
Empty