PHP - Get values from Array - php

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

Related

How could I get value in an array or how could I convert array to string?

$tId = $this->its_model->get_status_type($property_id);
print_r($tId);
$tsId = $this->its_model->get_sub_status_type($tId);
The $tId returns this:
Array ( [0] => Array ( [tId] => 2 ) )
And now I need to use the value 2 in the second line of code. As it is in the form of array I am getting an error. How could I get the value only that is 2?
So if
$tId is
Array ( [0] => Array ( [tId] => 2 ) )
it should be simply
echo ( $tId[0]['tId'] ) // should print 2
I don't know what Data you are trying to return but if your data is one dimensional, instead of returning
$query->result_array();
you can simply use
$query->row_array();
This returns a single row/flat array rather than a multidimensional array that you need to select the index or loop through. It will be as easy as
echo $tId['tId']
Alternatively you can return an object by using
$query->row() or $query->result();
You can then call the value by using
echo $tId->tId;

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'.

Wordpress PHP MySQL query with a multidimensional array

When I run the below PHP in WordPress without the foreach I successfully get printed a multidimensional array. When I use the foreach it returns an error 500 I am just trying to loop through the results so I am able to select each name and then push it to another array.
If someone could assist me with looping through this array, that would be great!
Array
(
[0] => stdClass Object
(
[term_taxonomy_id] => 26
[taxonomy] => product_brand
[name] => Authentic Cheese
[slug] => authentic-cheese
)
[1] => stdClass Object
(
[term_taxonomy_id] => 27
[taxonomy] => product_brand
[name] => Robot
[slug] => robot
)
)
PHP
$q2 = "SELECT t.term_taxonomy_id, t.taxonomy, e.name, e.slug
FROM wp_term_taxonomy t
INNER JOIN wp_terms e ON t.term_taxonomy_id = e.term_id
WHERE taxonomy = 'product_brand'";
$r2 = $wpdb->get_results($q2);
print_r($r2);
foreach ($r2 as $row) {
echo $row['name'];
}
You have an array of objects in the result. So use:
foreach ($r2 as $row) {
echo $row->name;
}
You have a 1 dimensional array of objects, instances of stdClass, to be exact:
Array
(
[0] => stdClass Object //<== stdClass OBJECT!!
That means that you can either use the objects, and access the names like you would with any object:
foreach ($array as $row)
{
echo $row->name, PHP_EOL;
}
Or, if you really want to, you can simply cast the objects to arrays:
foreach ($array as $k => $o)
{
$array[$k] = (array) $o;//cast and re-assign
}
Next time you loop over the $array, the objects will be gone, and you'll get associative arrays instead... really, though, this cast business is just overhead, I'd really just use the objects if I were you.
Of course, if you can change the fetch mode, you could change it so that all results are fetched as associative arrays.
According to the wordpress documentation, you can pass a second argument to the get_results method, that specifies the fetch method:
$r2 = $wpd->get_results($q2, ARRAY_A);
Would be the best way to ensure that $r2 is actually an array of associative arrays
To quote the documentation on which I base this:
Generic, mulitple row results can be pulled from the database with get_results. The function returns the entire query result as an array, or NULL on no result. Each element of this array corresponds to one row of the query result and, like get_row, can be an object, an associative array, or a numbered array.
<?php $wpdb->get_results( 'query', output_type ); ?>
query
(string) The query you wish to run. Setting this parameter to null will return the data from the cached results of the previous query.
output_type
One of four pre-defined constants. Defaults to OBJECT. See SELECT a Row and its examples for more information.
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.
Note from your print_r that it's an array of objects not an array of arrays. So you need to do
foreach ($r2 as $object) {
echo $object->name;
}
You can use wp_list_pluck in WordPress:
<?php names = wp_list_pluck( $your_array, 'name' ); ?>

wordpress $wpdb select results to an array

$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}

PHP rewriting a json array (Undefined offset)

I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];

Categories