Extract data from curl with a 2nd digit - arrays

I would like to extract data from a json file. For now i want to take the value of that array but I can't really find a way to solve the problem with the second 0/1/2.
I have already tried this, but unfortunately it does not work
<?php echo $datasearch_stat[0]->statistics->0->value;?>
<?php echo $datasearch_stat[0]->statistics->[0]->value;?>
My code:
<?php
$url_stat = "....";
$curl_stat = curl_init($url_stat);
curl_setopt($curl_stat, CURLOPT_URL, $url_stat);
curl_setopt($curl_stat, CURLOPT_RETURNTRANSFER, true);
//for debug only!
curl_setopt($curl_stat, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl_stat, CURLOPT_SSL_VERIFYPEER, false);
$stat = curl_exec($curl_stat);
curl_close($curl_stat);
$datasearch_stat = json_decode($stat);
?>
Value: <?php echo $datasearch_stat[0]->statistics->0->value;?>
Json file:
Thanks in advance!

echo json_decode($stat,true)[0]["statistics"][0]["value"];
notice the "true" there, turns everything into arrays so you don't have to guess which parts are converted to objects and which are converted to arrays, they're all arrays with the 2nd true argument.

Related

Simple way to array to strin conversion

I need to convert the laravel form validation error array to a string only the values.
I do not want use json_encode.
in my case I am trying to do the save edit function with ajax.
so I decided to get the form validation errors as a string from the controller.
writing a call back function to convert the array of errors to a string, so the error key may change form to form. how do I do this.
Is there a better way to handle this situation..
This is what I tried
if ($validator->fails()) {
$error = $validator->getMessageBag()->toArray();
echo '<pre>'; print_r($error); echo '</pre>';
$error_str = '';
foreach ($error as $row){
$error_str .= $row[0].'</br>';
}
echo $error_str;
}
You should not use $row[0]because it will only fetch first error from a list of errors of specific field.
Here is a solution to get all errors in one string with its field name.
$str = implode("\n",
array_map( function( $e, $key ){
return $key.": ". implode(", ",$e);
}, $error, array_keys($error) )
);
print_r($str);

json_decode access nested array with multiple identical keys

I am trying to access a specific value from an array, but have difficulties fetching it. More specifically it is the value DealerCarExtended-->ImageIds-->ImageId-->Id, but my problem is that ImageIds is an array with multiple ImageId's. I use son_decode, but the code below obviously doesn't work.
$response = file_get_contents( 'http://api.autoit.dk/car/GetCarsExtended/391B093F-BB4A-45AA-BEFF-7B33842401EA' );
$myArray = json_decode($response,true);
$myArray = $myArray[0];
echo $myArray['ImageIds']['ImageId']['Id'];
I'm sure that this is trivial for most of you guys but i'm a newbie in this :-)
A working example :
$response = file_get_contents( 'http://api.autoit.dk/car/GetCarsExtended/391B093F-BB4A-45AA-BEFF-7B33842401EA' );
$myArray = json_decode($response,true);
$myArray = $myArray[0];
# fetching second array item :
echo $myArray['ImageIds'][1]['Id']

Json decoding arrays [duplicate]

I have a json string like this:
$fields_string = '
{"fields":
{"customers":[{"name":"john","id":"d1"},
{"name":"mike","id":"d2"},
{"name":"andrew","id":"d3"},
{"name":"peter","id":"d4"}]
}
}'
How can I print each name? I will use them later in a html select options, I know how to do that. But I couldn't get the string out.
Here are something I tried:
$obj = json_decode($fields_string);
$fields_detail = $obj-?{"fields"}->{"customers"};
at this point, I am able to print the customer array out by echo json_encode($fields_detail), but before that, I want to get the name break down using foreach. I tried several times, it didn't work. Can anyone help please.
Thanks!
Customers is an array of objects so iterating over each object and reading the property should work.
foreach ($fields_detail as $customer) {
echo $customer->name;
}
Something like this:
$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
echo $customer['name'];
}
Access the names via fields->customers:
$obj = json_decode($fields_string);
foreach($obj->fields->customers as $customer)
{
echo $customer->name . "\n";
}
Demo
foreach($obj->fields->customers as $fields)
echo $fields->name;

How to fetch and display an array using PDO?

I understand there are MANY ways to do all of this, but trying to do it the best way.
I have created the db parameters, dns, dbh, sth, sql and generally quite happy with the result up to ... well ... the result part.
<?php
// db parameters
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
// driver invocation (dsn is short for data source name)
$dsn = "mysql:host=$dbhost;dbname=$dbname";
// create db object (dbh is short for database handle)
$dbh = new PDO($dsn, $dbuser, $dbpass);
// execution of database query (sth is short for statement handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
NOT SURE WHAT TO PUT BELOW.... (A) or (B)
I just want to present a simple array of the data. One row from the table per line.
Option A
echo $_POST['fieldname1'];
echo $_POST['fieldname2'];
echo $_POST['fieldname3'];
Option B
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row[fieldname1],'<br>';
}
AND I AM CONFIDENT WITH THE ENDING
$dbh = NULL;
?>
Any advise would be GREATLY appreciated.
UPDATED CODE: (Produces nothing on the page)
<?php
// db parameters
$dbhost = "localhost";
$dbname = "theaudit_db1";
$dbuser = "theaudit_user";
$dbpass = "audit1999";
$dsn = "mysql:host=$dbhost;dbname=$dbname"; // driver invocation (dsn is short for Data Source Name)
try {
$dbh = new PDO($dsn, $dbuser, $dbpass); // connect to new db object (dbh is short for Database Handle)
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to enable exceptions
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // set the PDO emulate prepares to false
// execute query to database (sth is short for Statement Handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = NULL;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Though I can't get what's the connection between A anb B, I can answer the
I just want to present a simple array of the data. One row from the table per line.
question.
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
where $data is a sought-for array.
The problem with your updated code is simple - you arent echo'ing your data out. You need to add something like..
foreach($data as $arKey=>$dataRow){
foreach($dataRow as $arKey=>$rowField){
echo $rowField.','; //concat with a ',' to give csv like output
}
echo '<br>'; //to get to next line for each row (may want to trim the last ','
}
I am also confused by the reference to $_POST. It is true both are associate arrays but that does not mean that the $_POST option is viable - the data would only be available in the $_POST if you put it there (eg $_POST = $data) which would be pointless. Or if you had posted the data from somewhere else. Neither seem to fit what you are asking so I would forget about the $_POST and just figure out how you access your multi dimensional $data array. There is endless tut's on this subject. Try using
var_dump($data)
to see whats inside that should help you visualise what is going on.
NOTE: in option B you are not correctly concatenating or referencing your array it should be:
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $rows[fieldname1].'<br>'; //$row doesnt exist its $rows and you use . to concat not ,
}
Ah yes and probably better to use unset rather than setting $dbh to equal null
unset($dbh);

preg_replace multiple problem

I am trying to replace multiple urls in a pagination element with a new url.
The replacement works fine when there is one occurrence of the url i.e. prev and next, but it breaks on breaks on the Pagination Numbers. It brings the first and last number links together. How do I get the preg_replace function realize that there are multiple occurrences of the links that need replacing?
<?php
$pattern = '/\/(.+)\/page:(\d)/S';
$replacement = $uurl.'page:$2';
echo preg_replace($pattern, $replacement,$paginator->prev('<< '.__('previous', true), array('url' => $paginator->params['pass']), null, array('class'=>'disabled'))).' | ';
echo preg_replace($pattern, $replacement,$paginator->numbers());
echo preg_replace($pattern, $replacement,$paginator->next(__('next', true).' >>', array('url' => $paginator->params['pass']), null, array('class'=>'disabled')));
?>
Try this:
$pattern = '/\/(.+?)\/page:(\d)/S';
Your .+ is greedy. In other words, it's sucking up everything between the first / and the last /page:.
The ? operator will make it match the minimum instead.

Resources