I cannot get any output from my multi-dimensional array. I'm trying to get my data using the push_array method.
I would like to get my output as:
John, 1001
Tom, 1002
Jerry, 1003
Sarah, 1004
However, I'm not getting any output. I know the array is working though as I get the following output when I echo $message and do not use $id and $name in my output foreach array.
Current output: (when echoing $message)
1
2
3
4
But nothing gets shown when I use $id and $name as shown here.
<ul class="result"><?php
foreach ($output as $message) {
$id = $message[1][0];
$name = $message[1][1];
?><li>
<?php echo $name; ?>
</li><php } ?>
</ul>
Here is my full code:
<?php
$Download = new Download();
$result = array(); //store results of upload
try {
$Download->showDBFiles();
$output = $Download->getMessages();
} catch (Exception $e) {
$result[] = $e->getMessage();
}
?>
<h2>Output</h2>
<?php if ($output) { ?>
<ul class="result">
<?php foreach ($output as $message) {
$id = $message[1][0];
$name = $message[1][1];
?>
<li><?php echo $name; ?></li>
<?php } ?>
</ul>
<?php } ?>
Function where arrays are defined
protected $messages = array();
public function showDBFiles() {
global $database;
$values=array();
$sql = "SELECT resume_id, resume_title FROM ".self::$table_name;
$result = $database->query($sql);
if(mysqli_num_rows($result)==0){
$this->messages[] = "Database is empty";
}else{
while(list($id, $name) = mysqli_fetch_array($result)){
array_push($this->messages, array($id, $name));
}
}
}
public function getMessages()
{
return $this->messages;
}
UPDATE:
After using the suggestion by jedrzej.kurylo I'm able to have the $id and $name values as shown in my var_dump output:
array(4) { [0]=> array(2) { [0]=> string(2) "73" [1]=> string(2) "qd" } [1]=> array(2) { [0]=> string(2) "72" [1]=> string(3) "jav" } [2]=> array(2) { [0]=> string(2) "70" [1]=> string(4) "da12" } [3]=> array(2) { [0]=> string(2) "71" [1]=> string(3) "jav" } }
However for some reason that I'm unsure of my output is now this:
d
a
a
a
The problem is with how you use array_push here:
$this->messages[] = array_push($values, array($id, $name));
array_push does not return updated array but the new number of items in the array - see http://php.net/manual/en/function.array-push.php. That's why you're getting increasing integers in your output.
Do the following instead:
while(list($id, $name) = mysqli_fetch_array($result)){
array_push($this->messages, array($id, $name));
}
or just
while(list($id, $name) = mysqli_fetch_array($result)){
$this->messages[] = array('id'=>$id, 'name'=>$name);
}
Then you can access $id and $name like this:
$id = $message['id'];
$name = $message['name'];
Related
I am new to JSON and I am wondering how i could format my JSON file so I will be able to render it in a barchart.
I've got the following PHP code:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
file_put_contents('jsonoutput.json', json_encode($myArray));
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>
My actual output:
(given a gene (xkr4) as input)
{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}
How I'd like to get my output:
{"genename":"xkr4",{"TA11MEAN":"974.25"},{"TA11STD":"99.0085223605"},{"TA21MEAN":"710.75"},{"TA21STD":"115.79831605"},{"TA22MEAN":"736.5"},{"TA22STD":"115.79831605"},{"TA23MEAN":"903.75"},{"TA23STD":"107.283211641"},{"TB11MEAN":"799.25"},{"TB11STD":"97.2660655111"},{"TB21MEAN":"658"},{"TB21STD":"91.7959694104"},{"TB22MEAN":"592.75"},{"TB22STD":"70.9379129944"},{"TB23MEAN":"864"},{"TB23STD":"92.7280971443"}}
If someone could give me direction on this (or solve it) That would be great!
Thanks in advance :)
I would suggest you to first check how are you getting back your data in array.
$myArray[] should have the data populated as shown below. Then use JSON_PRETTY_PRINT.
/*USED TO SHOW FULL ARRAY SIZE*/
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
$myArray=array("genename"=>array(array("xkr4"=>array(
array("TA11MEAN"=>"974.25","TA11STD"=>"99.0085223605"),
array("TA21MEAN"=>"710.75","TA21STD"=>"115.79831605"),
array("TA22MEAN"=>"736.5","TA22STD"=>"115.79831605"),
array("TA23MEAN"=>"903.75","TA23STD"=>"107.283211641"),
array("TB11MEAN"=>"799.25","TB11STD"=>"97.2660655111"),
array("TB21MEAN"=>"658","TB21STD"=>"91.7959694104"),
array("TB22MEAN"=>"592.75","TB22STD"=>"70.9379129944"),
array("TB23MEAN"=>"864","TB23STD"=>"92.7280971443"),
))));
$jsonData=json_encode($myArray,JSON_PRETTY_PRINT);
var_dump($jsonData);
$json_from_database='[{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}]';
//print decode array from databse
$decoded=json_decode($json_from_database);
var_dump($decoded);
foreach ($decoded[0] as $key => $value) {
echo "\n ";
print $key;
print " " .$decoded[0]->$key;
}
array(1) {
[0]=>
object(stdClass)#1 (17) {
["genename"]=>
string(4) "xkr4"
["TA11MEAN"]=>
string(6) "974.25"
["TA11STD"]=>
string(13) "99.0085223605"
["TA21MEAN"]=>
string(6) "710.75"
["TA21STD"]=>
string(12) "115.79831605"
["TA22MEAN"]=>
string(5) "736.5"
["TA22STD"]=>
string(12) "115.79831605"
["TA23MEAN"]=>
string(6) "903.75"
["TA23STD"]=>
string(13) "107.283211641"
["TB11MEAN"]=>
string(6) "799.25"
["TB11STD"]=>
string(13) "97.2660655111"
["TB21MEAN"]=>
string(3) "658"
["TB21STD"]=>
string(13) "91.7959694104"
["TB22MEAN"]=>
string(6) "592.75"
["TB22STD"]=>
string(13) "70.9379129944"
["TB23MEAN"]=>
string(3) "864"
["TB23STD"]=>
string(13) "92.7280971443"
}
}
genename xkr4
TA11MEAN 974.25
TA11STD 99.0085223605
TA21MEAN 710.75
TA21STD 115.79831605
TA22MEAN 736.5
TA22STD 115.79831605
TA23MEAN 903.75
TA23STD 107.283211641
TB11MEAN 799.25
TB11STD 97.2660655111
TB21MEAN 658
TB21STD 91.7959694104
TB22MEAN 592.75
TB22STD 70.9379129944
TB23MEAN 864
TB23STD 92.7280971443
This is how your data looks like from database it is a array of rows row is a object
I solved it:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
//file_put_contents('jsonoutput.json', json_encode($myArray));
$json = json_encode($myArray);
$array = json_decode($json, true);
$new_array = array();
foreach( $array as $key => $value ){
$newarray[] = array($key=>$value);
}
echo json_encode($newarray);
file_put_contents('jsonoutput.json', json_encode($newarray));
}
$result->close();
$mysqli->close();
?>
I'm accessing data from an API using json_decode. The code I have returns the array of ALL the date (see below), but I want to return specific data such as 'name' or 'locale'.
$json_string = 'http://api.duedil.com/open/search?q=Surfing%20Sumo&api_key=THE-API-KEY';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo '<pre>';
var_dump($obj);
This is what is returned (this is abbreviated to save space here):
array(1) {
["response"]=>
array(2) {
["pagination"]=>
string(79) "http://api.duedil.com/open/search?query=Duedil&total_results=6&limit=5&offset=5"
["data"]=>
array(5) {
[0]=>
array(4) {
["company_number"]=>
string(8) "06999618"
["locale"]=>
string(14) "United Kingdom"
["name"]=>
string(14) "Duedil Limited"
["uri"]=>
string(51) "http://api.duedil.com/open/uk/company/06999618.json"
}
You could just use
$name = $obj['response']['data'][0]['name'];
$locale = $obj['response']['data'][0]['locale'];
if you have multiple return values, you could loop over them
foreach ($obj['response']['data'] as $item) {
$name = $item['name'];
$locale = $item['locale'];
}
try this sample code:
<?php
$data = isset($obj['response']['data'])?$obj['response']['data']:FALSE;
if(is_array($data))
{
foreach ($data as $value) {
echo $value['name'];
echo $value['locale'];
}
}
I have an textfield where you can add comma separated values: Address1, Adress2
When you hit submit, information will be returned for each adress you typed in.
I want to treat the information as an array, and use the separated values that user user entered, as keys in the array.
I have the following code:
if(isset($_POST['submit']))
{
$addresses = explode(",", $_POST['addresses']);
$ort = $_POST['omrade'];
$obj = array();
foreach($addresses as $address)
{
echo $newSpider->fetchPage($address, $ort, $offst=0);
if(!isset($obj[$address]))
{
$obj[$address] = array();
echo "<pre>";
var_dump($address);
echo "</pre>";
}
}
}
When I type in two values, Adress1 and Adress2, the output of var_dump is:
array(1) {
["Address1"]=>
array(0) {
}
}
array(2) {
["Address1"]=>
array(0) {
}
["Address2"]=>
array(0) {
}
}
I want it to be like this:
array(1) {
["Address1"]=>
array(0) {
}
["Address2"]=>
array(0) {
}
}
What am I doing wrong? Anyone who can help me and explain?
Your code basically var_dumps for every loop. Just var_dump it after loop. Try this
if(isset($_POST['submit']))
{
$addresses = explode(",", $_POST['addresses']);
$ort = $_POST['omrade'];
$obj = array();
foreach($addresses as $address)
{
echo $newSpider->fetchPage($address, $ort, $offst=0);
if(!isset($obj[$address]))
{
$obj[$address] = array();
echo "<pre>";
echo "</pre>";
}
}
var_dump($address);
}
I have the following query:
$sth = $this->db->prepare("SELECT * FROM comment WHERE status = 1");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$reviews = array();
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
return $reviews;
}
Which returns the following for var_dump($this->reviews):
array(9) {
[0]=> array(1) { ["name"]=> string(5) "name1" }
[1]=> array(1) { ["comment"]=> string(8) "comment1" }
[2]=> array(1) { ["star"]=> string(1) "4" }
[3]=> array(1) { ["name"]=> string(5) "name2" }
[4]=> array(1) { ["comment"]=> string(8) "comment2" }
[5]=> array(1) { ["star"]=> string(1) "4" }
[6]=> array(1) { ["name"]=> string(5) "name3" }
[7]=> array(1) { ["comment"]=> string(8) "comment3" }
[8]=> array(1) { ["star"]=> string(1) "4" }
}
How can I use foreach to display name, comment, star by row?
I.e.:
name1, email1#email.com, comment1
name2, email2#email.com, comment2
name3, email3#email.com, comment3
I know it should be something like:
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
But this gives me Notice: Undefined index: name. How do I define the index?
You are setting up the insert into the array incorrectly:
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
The shorthand [] inserts a new element each and every single time, you want to actually insert an array AS the element.
while($row = $sth->fetch()){
$revArr=array('name' => $row['name'], 'comment' => $row['comment'], 'star' => $row['star']);
$reviews[]=$revArr;
}
Edit: Now change your second foreach to this:
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
You need to generate an array of arrays. Something like
while($row = $sth->fetch()){
$reviews[] = array('name' => $row['name'], 'comment' => $row['comment'], 'star'=> $row['star']);
}
Now your $reviews object will have just as many elements as there were rows in the query result, and you can print it any way you want.
As for printing (which I think is where your error message is coming from):
foreach($reviews as $thisValue) {
echo "Name: ". $value['name'];
}
should work.
You should use your foreach loop like this:
foreach( $this->reviews as $value){
echo "Name:". $value['name'] . "Email:" . $value['email'] . "Comment:" . $value['comment'];
}
Notice how i use $value instead of $this->reviews inside the loop.
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
this is not the right way, because now you are working on $key so write -
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
you can do it as follow:
$reviews = array();
while($row = $sth->fetch()){
$reviews[] = array($row['name'], $row['comment'], $row['email'], $row['star']);
}
and then you can do a heredoc:
$str = '';
foreach( $this->reviews as $review ){
$str .=<<<html
name: {$review['name']}
email: {$review['email']}
comment: {$review['comment']}
start: {$review['star']}
html;
}
finally i echo everything:
echo $str;
I think this is much cleaner, and you can add any html.
$images = valley_images();
var_dump($images);
$sorted_data = array();
foreach($images as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $images;
}
}
ksort($sorted_data);
The error is appearing on this line:
$sorted_data[$value][] = $images;
When I do the var dump of images I receive this:
array(2) {
[0]=> array(2) {
["id"]=> string(2) "17" ["timestamp"]=> string(10) "1359797773"
}
[1]=> array(2) {
["id"]=> string(2) "20" ["timestamp"]=> string(10) "1359934365"
}
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);