Php, array printing - php

I have an array:
Array (
[0] => Array (
[userid] => 5
[0] => 5
[firstname] => DALPA
[1] => DALPA
[lastname] => DALPA
[2] => DALPA
)
)
when i try to print this using foreach loop i get an error
<?php
include('../conn.php');
$q = $_GET['q'];
$adress = $conn->prepare("SELECT * FROM user WHERE firstname= :q ");
$adress->bindValue(':q', $q, PDO::PARAM_STR);
$adress->execute();
$result = $adress->fetchAll();
foreach($result as $item){
echo $item . "\n";
}
?>
Error:Array to string conversion in C:\xampp\htdocs\admin\adres\adres.php on line 13
Been asked many times but none of them solved my problem, what should I do?

php's echo statement can only echo strings. If it is not a string but a number for example, it will try to converse the given value to a string. With an array that is not possible.
In your case you are looping trough an array containing another array. As the error tells you, it fails to echo an array because it expects something that can be converted to a string.
So either use
foreach($result as $item) {
print_r($item) // or var_dump($item)
}
Or echo key => value pairs using
foreach($result as $item) {
echo $item['firstname'] . "\n";
echo $item['lastname'] . "\n";
... and so on
}
If you are expecting only one item to be returned, update your query by using fetch instead of fetchAll, which will return only one row.
You can then omit the unnecessary foreach loop.
And if you realy want to echo the array, you have to do the conversion manualy by using json_encode, which will convert the array to an JSON string.
echo json_encode( $result );

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

Using the nth item in a php array

I have created an array, as follows:
$results = array();
do {
$results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));
print_r($results);
This prints out the array like this:
Array (
[0] => Array (
[productName] => product1
)
[1] => Array (
[productName] => product2
)
[2] => Array (
[productName] => product3
)
I want to now use say the second item in the array in another mysql query.
But I cannot define it. I have tried
$results[1];
but this does not work.
So in effect, if I echo the second item, it would print 'product2'.
You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php
You are using a nested array, so you have the access it like this:
echo $results[1]['productName'];
Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].
In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.
while ($row_products = mysql_fetch_assoc($products)) {
$results[] = $row_products;
}
try this :
echo $results[1]['productName'] ;
$results[1] is an array, If you want see the array print_r($results[1]);

php array variable

in my script,
$value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
this works well
i have a variable $names which is a mysql result, which has data "DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer" like an array data.
but when i place the variable inside like $value= array($names); instead of $value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); , i am getting result "Bloomsberry is not there " instead of expected "Bloomsberry is there inside the array"
I suspect that the " signs get escaped and that also the array is passed as an single string. You will have to split the string to an array. If I where you I would submit to mysql: "DK,Bloomsberry,McGrawHill"etc and then do
<?php
$string = "DK,Bloomsberry,McGrawHill,OXFORD,DC Books,Springer";
$array = explode(",", $string);
if(in_array("Bloomsberry",$array)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
The explode command returns an array split on the commas.
I hope this works for you
If $names is already an Array, then array($names) is an Array containing one element (the one element is your $names array).
If you want to assign $value to the array $names, you simply use the assignment operator:
$value = $names;
Then do your conditional in_array("Bloomsberry", $value);. Or you could just avoid the assignment and do in_array("Bloomsberry", $names).
Notice the following difference:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
print_r($value);
/* produces:
Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
*/
where as:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
$newValue = array($value);
print_r($newValue );
/* produces:
Array
(
[0] => Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
)
*/
in_array("Bloomsberry", $newValue) will only return true if "Bloomsberry" is a value in the first dimension of the array. However the only first dimension element in $newValue is the $value array.
Issue:
This is because in_array starts checking at the root node, and depending on how many levels the needle has depends in how many levels it checks within the haystack
An example of the above:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a))
{
echo "'ph' was found\n";
}
$a is actually 2 levels of arrays, also called multi-dimensional.
Within your code your placing your root level array, into another array, thus the array of the DB Then becomes array(array("results")) this when you check the first node using in_array("string") it cant find it within the root haystack.
Possible Fix:
Just use the actual result as your in_array check, example:
while($row = mysql_fetch_array($result))
{
/*
$row is a single dimension and can be used like so:
*/
if(in_array("Bloomsberry"),$row))
{
//Echo your success.
}
}
try this
$name = '"DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"';
$name = str_replace('"', '', $name);
$value = explode(',', $name);
Now your below given code will work.
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}

PHP - Get values from Array

I am trying to retrieve a value from an Array. Here is the code:
$opt=get_records_sql($sql1);
print_object($opt);
$n = count($opt);
if (empty($opt)){
echo 'No options selected';
}
else{
$optno = $opt["subjectid"];
echo '<br>$optno = '.$optno;
}
I tried to use: $opt["subjectid"] but I get the following error:
Notice: Undefined index: subjectid
Contents of array:
Array
(
[1] => stdClass Object
(
[uname] => JHollands06
[tutor] => M LSt
[subjectid] => 1
[year] => 2010
[optid] => 1
)
)
How to I fetch the data subjectid which has value 1?
Method 1: Convert the object to an array by casting it.
$opt[1] = (array) $opt[1];
echo $opt[1]['subjectid'];
To convert all objects in an array (if there are more than one):
foreach ($opt as $k => $val) {
$opt[$k] = (array) $val;
}
Method 2: Simply call it as an object like it is already assigned.
echo $opt[1]->subjectid
There is a difference between an array and an object. An object contains variables that have to be called using the '->' and an array contains values which are associated with a specific key. As your output states, you have an array containing an stdClass object, not another array.
$opt is an array of rows. So you'd do something like this:
foreach($opt as $row)
{
echo $row['subjectid'];
}
Or just use an index:
$opt[0]['subjectid'];
Your array contains rows. It's not just one row. So you need to index it by row first.
edit: your rows are objects, my bad. So it should be
$opt[1]->subjectid

Categories