I have the following code:
$res = $db->getArticles($db);
$hey = print_r($res, TRUE);
echo $hey['0'];
Here is the code for $db->getArticles:
public function getArticles() {
$array = array();
try {
$sth = $this->db->prepare("SELECT * FROM posts ORDER BY id");
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$array[] = $row;
}
return $array;
} catch (Exception $e) {
}
}
The logic is that the function queries the database and puts everything into an array. The number of rows in the table will always be pretty low, so performance isn't an issue.
The following is the output of the first code snippet above:
echo $hey['0']; // prints "A" (without the quotes).
echo $hey['1']; // prints "r"
echo $hey['2']; // prints "r"
echo $hey['3']; // prints "a"
echo $hey['4']; // prints "y"
As you can see, it spells out the word "Array."
echo $hey prints the following:
Array ( [0] => Array ( [id] => 1 [author] => 0 [content] => This Is a Test [publication_date] => 1380380992 ) )
My end goal is to store each individual value into a variable and do something with it. This would all happen inside a for loop which runs on the array so I can get information from each row.
What am I doing wrong?
$hey = print_r($res, TRUE);
This will return a string that gives the info of the array $res. If you echo it, you should expect to see the same as what print_r($res); displays, as you've shown. $res is already an array of your query data, so loop over that.
foreach($res as $row) { //row loop
foreach($row as $col) { //column loop
//do something
}
}
$array = array( array( ID => 1,
author => 0,
content => "This Is a Test",
publication_date => 1380380992
)
);
echo $array['0']['author'];
This works for me...
just echo echo $array['0']['author']; and replace author by the field you need.
Related
I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605
This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 7 years ago.
I am trying to properly create and encode and array using json_encode php function. The array i am trying to encode is $myarray . From my code if do
$myarray = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
then
echo json_encode($myarray) ; // this works but only one item is pushed to my array
if i do
$myarray[] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array
result is nothing.
what i am missing ?
see full code below on what i have so far done.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
//Push values to my array
$myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
//
}
//Then try to encode $myrray but this fails
$jsonstring = json_encode($myarray);
if ($jsonstring!==false)
{
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
///////////////////////
/////////////////////////
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
please help. thank you.
The right way to create the array would be like this:
$myarray = array(
array(
'name' => 'bla',
'id' => 1
), array(
'name' => 'blas',
'id' => 2
)
);
This part of your code is perfectly fine.
$data = array() ; //create new empty array
//loop through the array
foreach($myarray as $keys => $h)
{
$data [] = $h;
}
//encode
echo json_encode($data) ; //this fails silently
If you run the code, it works perfectly fine:
[{"name":"bla","id":1},{"name":"blas","id":2}]
Your foreach() loop creates a new array $data with the same entries (also arrays) as the $myarray contains. So, you could directly encode $myarray like this:
<?php
$myarray = array(
array('name' =>' Agrolait', 'id' => 6 ),
array('name' => 'Agrolait, Michel Fletcher', 'id' => 31 ),
array('name' => 'Agrolait, Thomas Passot', 'id' => 30 )
);
$jsonstring = json_encode($myarray);
if ($jsonstring!==false) {
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
?>
Which produces this JSON string:
[{"name":" Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}]
json_encodereturns the value FALSE if something went wrong, and the encoded string else. If you check the result from it you at least know when it fails.
Thanks for your suggestion have solved this. My string data was not properly encoded using utf-8 as suggested by http://nl3.php.net/manual/en/function.json-encode.php. Check my answer below
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
$myarray [] = array('name' =>utf8_encode($value['display_name']->scalarval()),'id' => utf8_encode($value['id']->scalarval())) ;
//
//array_push($better, $myarray) ;
}
//echo '<pre>';
//print_r($myarray) ;
//echo '</pre>';
echo json_encode($myarray);
exit;
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
I have a result from my db query that's look like this when dump and the query is doing what is expected, but I am have a little problem getting the array values. I am using PHP PDO to get the result.
$result = $_stmt->fetchAll();
$row = count($result);
print_r($result);
Array ( [0] => Array ( [SUM(od_price * od_qty)] => 69.85 [0] => 69.85 )
[1] => Array ( [SUM(od_price * od_qty)] => 13.97 [0] => 13.97 )
) 69.8513.97
You can see that the result contains both an array and a string values. I have an option to get either the array or the string value. But I would rather to get the array values since the the string values are all togather. Can some one please explain what I am doing that's wrong in the foreach loop?
if($row == 2)
{
foreach ($result as $k)
{
echo $price_1 = $k[0][0]; // expected 69.85
echo $price_2 = $k[0][1]; // expected 13.97
}
unset($k);
}
I need to get the expected values, but instead I am getting the string values that are all togather.
After reviewing the solutions below, here is what I came up with that works well for what I wanted.
$result = $_stmt->fetchAll();
$row = count($result);
$price = "";
if($row == 2)
{
foreach ($result as $k)
{
$price .= $k[0].',';
}
}
// remove the last comma
$price = substr($price, 0, -1);
list($totalPurchase, $shippingCost) = explode(",",$price);
$orderAmount = $totalPurchase + $shippingCost;
echo 'The amount is: '.$orderAmount;
Try storing the values in an array instead of echoing them..
$price_1 = array(); $price_2 = array();
if($row == 2)
{
foreach ($result as $k)
{
array_push($price_1, $k[0][0]); // expected 69.85
array_push($price_2, $k[0][1]); // expected 13.97
}
// print_r($price_1); //should store all the price1s
// print_r($price_2); // should store all the price2s.
// uncomment to these lines to view array contents
}
Although you need to learn multidimensional arrays and foreach in general, to solve this particular task you need to use fetchAll with little addendum:
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($result as $k)
{
echo $k;
}
replace your loop with this:
foreach ($result as $k) // iterate through all datasets
{
echo $k[0]; // echo price of dataset
}
It's already been answered, but i've seen in a comment that you want them seperate. So just concat a "<br>" or a new line space after your echo:
foreach ($result as $k)
{
echo $k[0]."<br>";
}
I have an array which comes from a report.
This report has info similar to:
157479877294,OBSOLETE_ORDER,obelisk,19/01/2013 01:42pm
191532426695,WRONG_PERFORMANCE,g3t1,19/01/2013 01:56pm
159523681637,WRONG_PERFORMANCE,g3t1,19/01/2013 01:57pm
176481653889,WRONG_PERFORMANCE,g4t1,19/01/2013 01:57pm
167479810401,WRONG_PERFORMANCE,g4t1,19/01/2013 02:00pm
172485359309,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
125485358802,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
172485359309,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
125485358802,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
What I need to do is get the total of each type of error and the location so for the first would be error: 'OBSOLETE_ORDER' and location: 'obelisk'. I have tried to do this a number of ways but the best I can come up with is a multi dimensional array:
$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
$line_of_text = fgetcsv($error_handle, 1024);
$errorName = $line_of_text[1];
$scannerName = $line_of_text[2];
if($errorName != "SCAN_RESULT" && $errorName != "" && $scannerName != "SCAN_LOGIN" && $scannerName != "")
{
$errorsArray["$errorName"]["$scannerName"]++;
}
}
fclose($error_handle);
print_r($errorsArray);
gives me the following:
Array ( [OBSOLETE_ORDER] => Array ( [obelisk] => 1 ) [WRONG_PERFORMANCE] => Array ( [g3t1] => 2 [g4t1] => 2 [g4t2] => 2 ) [DAY_LIMIT_EXCEEDED] => Array ( [obelisk] => 2 ) )
which is great...except how do I then take that apart to add to my sql database?! (I am interested in getting the key and total of that key under the key the array is under)
and then add it to the tables
-errors-
(index)id_errors
id_event
id_access_scanner
id_errors_type
total_errors
-errors_type-
(index)id_errors_type
name_errors_type
-access_scanner-
(index)id_access_scanner
id_portal
name_access_scanner
PLEASE HELP!
Thanks!
A multidimensional array is more than you need. The approach to take is to create your own string ($arrayKey in my example) to use as an array key that combines the scanner name and the error so that you can get a count.
//this is the array containing all the report lines, each as an array
$lines_of_text;
//this is going to be our output array
$errorScannerArray = array();
//this variable holds the array key that we're going to generate from each line
$arrayKey = null;
foreach($lines_of_text as $line_of_text)
{
//the array key is a combination of the scanner name and the error name
//the tilde is included to attempt to prevent possible (rare) collisions
$arrayKey = trim($line_of_text[1]).'~'.trim($line_of_text[2]);
//if the array key exists, increase the count by 1
//if it doesn't exist, set the count to 1
if(array_key_exists($arrayKey, $errorScannerArray))
{
$errorScannerArray[$arrayKey]++;
}
else
{
$errorScannerArray[$arrayKey] = 1;
}
}
//clean up
unset($line_of_text);
unset($arrayKey);
unset($lines_of_text);
//displaying the result
foreach($errorScannerArray as $errorScanner => $count)
{
//we can explode the string hash to get the separate error and scanner names
$names = explode('~', $errorScanner);
$errorName = $names[0];
$scannerName = $names[1];
echo 'Scanner '.$scannerName.' experienced error '.$errorName.' '.$count.' times'."\n";
}
$list = array();
foreach ($lines as $line) {
$values = explode(',' $line);
$error = $values[1];
$scanner = $values[2];
if (!isset($list[$error])) {
$list[$error] = array();
}
if (!isset($list[$error][$scanner])) {
$list[$error][$scanner] = 1;
} else {
$list[$error][$scanner]++;
}
}
To go through each result I just did the following:
foreach ($errorsArray as $errorName=>$info)
{
foreach ($info as $scannerName=>$total)
{
print "$errorName -> $scannerName = $total </br>";
}
}
and now will just connect it to the sql
With your edited question, this much simpler loop will work for you, you just need to then insert the data into your database inside the loop, instead of echoing it out:
$errorsArray = Array (
[OBSOLETE_ORDER] => Array (
[obelisk] => 1
)
[WRONG_PERFORMANCE] => Array (
[g3t1] => 2
[g4t1] => 2
[g4t2] => 2
)
[DAY_LIMIT_EXCEEDED] => Array (
[obelisk] => 2
)
)
foreach($errorsArray as $row => $errors) {
foreach($errors as $error => $count) {
echo $row; // 'OBSOLETE_ORDER'
echo $error; // 'obelisk'
echo $count; // 1
// insert into database here
}
}
OLD ANSWER
You just need a new array to hold the information you need, ideally a count.
Im assuming that the correct data format is:
$report = [
['157479877294','OBSOLETE_ORDER','obelisk','19/01/2013 01:42pm'],
['191532426695','WRONG_PERFORMANCE','g3t1','19/01/2013 01:56pm'],
['159523681637','WRONG_PERFORMANCE','g3t1','19/01/2013 01:57pm'],
['176481653889','WRONG_PERFORMANCE','g4t1','19/01/2013 01:57pm'],
.....
];
foreach($report as $array) {
$errorName = $array[1];
$scannerName = $array[2];
if(exists($errorsArray[$errorName][$scannerName])) {
$errorsArray[$errorName][$scannerName] = $errorsArray[$errorName][$scannerName] + 1;
}
else {
$errorsArray[$errorName][$scannerName] = 1;
}
}
I can get Tweets of users quite easily using PHP and JSON, but as soon as I use it to get a list of followers, I get errors. Both use JSON to return the values.
The code is:
$jsonurl = "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=mooinooicat";
$contents = file_get_contents($jsonurl);
$results = json_decode($contents, true);
echo "<pre>";
print_r($results);
echo "</pre>";
This gives me the following array:
Array
(
[next_cursor] => 0
[ids] => Array
(
[0] => 31085924
[1] => 53633023
[2] => 18263583
)
[previous_cursor] => 0
[next_cursor_str] => 0
[previous_cursor_str] => 0
)
How do I get the values of next_cursor and previous_cursor and how do I loop just through the ids array?
I want to parse the results for reading into a database.
you are not using the correct api try something like this
function fetch_twitter_count($user) {
if ($json = file_get_contents("http://api.twitter.com/1/users/show.json?screen_name=$user")) {
if(empty($json)) return 0;
$json = json_decode($json['body'], true);
return number_format(intval($json['followers_count']));
}
return 'API Error';
}
have not tested but should do what you want however keep inmind that you will want to use some sort of caching
Thanks for all the answers without examples...
I finally managed to figure it out using the example from Getting values from a single array
Here is the code:
foreach ( $results as $result ) {
if ( is_array( $result ) ) {
foreach ( $result as $sub_result ) {
// You can store this value in a variable, or output it in your desired format.
echo $sub_result . "<br />";
}
} else {
echo $result . "<br />";
}
}