I have a problem for like 4 hours.
$getrank = DB::table('users')->select('codes')->orderBy('codes', 'desc')->get();
with var_dump($getrank); I see whats in the array.
So I got this:
array(6) {
[0] => object(stdClass)#62 (1) {
["codes"]=> int(584)
}
[1] => object(stdClass)#64 (1) {
["codes"]=> int(117)
} [2] => object(stdClass)#65 (1) {
["codes"]=> int(88)
} [3] => object(stdClass)#66 (1) {
["codes"]=> int(66)
} [4] => object(stdClass)#67 (1) {
["codes"]=> int(53)
} [5] => object(stdClass)#68 (1) {
["codes"]=> int(37)
}
}
But I want them seperated.
I tried a lot!
In the end I thought this could be my answer:
echo $getrank[0]['codes'];
echo $getrank[1]['codes'];
echo $getrank[2]['codes'];
echo $getrank[3]['codes'];
echo $getrank[4]['codes'];
echo $getrank[5]['codes'];
But no.
I want a ranking, and I just need the first 5 ([0]-[4]). What else can I do?
In the end I want every value as a string!
Ok, now by reading your comments I understand what is the result you expect.
$getrank = array_map(
function ($user) { return $user->codes; },
DB::table('users')->orderBy('codes', 'desc')->take(5)->get()
);
Does that get you what you want?
Just use the pluck() (or lists(), alias of pluck()) method for this.
$codes = DB::table('users')->orderBy('codes', 'desc')->take(5)->lists('codes');
echo '<pre>';
foreach($codes as $key => $code) {
echo 'code '.$key.': '.$code.PHP_EOL;
}
echo '</pre>';
Documentation here
You can try to add toArray(), this will convert result from database to array, so you can use the code you've provided at the end of your question
$getrank = DB::table('users')->select('codes')->orderBy('codes', 'desc')->get()->toArray();
foreach($getrank as $rank) {
echo $rank['codes'];
}
And if you want to cast codes value to string, it is just echo (string) $rank['codes'];
Related
1. Extracted from my laravel controller:
..
..
$data = json_decode($response, true);
return $data;
..
..
return view('homepage')->with('homeExclusives', $homeExclusives);
Here is a sample of the returned data, just a short version, since the returned feed is very large, but this will give you an idea of the way it's structured.
array(4) {
["success"]=> bool(true)
["status"]=> int(200)
["bundle"]=> array(2) {
[0]=> array(631) {
["StreetDirPrefix"]=> string(2) "SW"
["DistanceToStreetComments"]=> NULL
}
[1]=> array(631) {
["StreetDirPrefix"]=> string(2) "NE"
["DistanceToStreetComments"]=> NULL
}
}
I need to extract "StreetDirPrefix" value from [0] and [1], but I always get an error. Can someone help?
For the data in your example you might use array_column and specify StreetDirPrefix as the column key.
$res = array_column($array["bundle"], "StreetDirPrefix");
print_r($res);
Php demo
Without knowing what error you are getting my solution would be something like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
}
}
?>
I always like to validate arrays, so if your $data variable or the $data["bundle"] subsection are not arrays then you will not get anything. Not even an error.
I have a working example here:
https://www.seeque-secure.dk/demo.php?id=PHP+how+to+loop+over+nested+JSON+Object
EDIT:
(if i understand you correct)
When you have validated your array all you have to do is repeat the inner validation like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
if (isset($tmpVal["UnparsedAddress"])) {
echo $tmpVal["UnparsedAddress"]."\n";
}
if (isset($tmpVal["SalePrice"])) {
echo $tmpVal["SalePrice"]."\n";
}
//...... ect.....
}
}
?>
I have an array in PHP:
(Name, level, score)
array(5) {
[0]=> string(28) "Mr Kowalchuk,9,4000000000"
[1]=> string(12) "Test Boy ,0,0"
[2]=> string(16) "Mr Test ,2,150"
[3]=> string(16) "Rutherford ,6,490"
[4]=> string(18) "Isaac Newton,3,235"
}
I am wishing to sort this array by the LAST column, the Score column. The code I am using is a slightly modified version of selection sort that allows me to sort by extracting the score parameter and using that value instead of the whole text (you can't sort by text in this case).
<?php
function getScoreValue($row) {
return (int)(explode(",", $row)[2]);
}
function minIndex($ma, $mi, $mj) {
if ($mi == $mj) {
return $mi;
}
$k = minIndex($ma, $mi + 1, $mj);
if (getScoreValue($ma[$mi]) < getScoreValue($ma[$k])) {
return $mi;
} else {
return $k;
}
}
function recursiveSelectionSort($ma, $mn, $mindex = 0) {
##echo 'Running...<br>';
if ($mindex == $mn) {
return -1;
}
$k = minIndex($ma, $mindex, $mn - 1);
if ($k != $mindex) {
$temp = $ma[$k];
$ma[$k] = $ma[$mindex];
$ma[$mindex] = $temp;
}
recursiveSelectionSort($ma, $mn, $mindex + 1);
}
I call my function with
recursiveSelectionSort($myarray, sizeof($mayarry));
However, using PHP's var_dump, it shows that the array stays the same and does not change. Any idea why this is happening and what I could do to fix it?
You do not need any recursion here. This is my idea.
Check the comment for explanation
$a1=array(
"Mr Kowalchuk,9,4000000000",
"Test Boy ,0,0" ,
"Mr Test ,2,150",
"Rutherford ,6,490" ,
"Isaac Newton,3,235" ,
);
//explode entires with comma to make nested array
$a2=array_map(function ($a) { return explode(",",$a); }, $a1);
//sort based on inner key
usort($a2, function ($a, $b) { return $a[2] - $b[2]; });
//implode back with comma to make it 1d array
$a3=array_map(function ($a) { return implode(",",$a); }, $a2);
echo "<pre>";
print_r($a3);
output
Array
(
[0] => Test Boy ,0,0
[1] => Mr Test ,2,150
[2] => Isaac Newton,3,235
[3] => Rutherford ,6,490
[4] => Mr Kowalchuk,9,4000000000
)
I'm creating a stock market portfolio website with the use of the IEX API but I'm currently stuck on one part when it comes to retrieving data as an array and then storing the values in a table.
Here's the code:
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=F,AAPL&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value)
echo '<br/>'. $divi.' : '. $value;
var_dump($div);
What I'm getting now is this:
Notice: Array to string conversion in
E:\XAMPP\htdocs\website2\test.php on line 34
F : Array
Notice: Array to string conversion in
E:\XAMPP\htdocs\website2\test.php on line 34
AAPL : Array
From the var_dump, I get this:
array(2) { ["F"]=> array(1) { ["stats"]=> array(1) {
["dividendRate"]=> float(0.13) } } ["AAPL"]=> array(1) { ["stats"]=>
array(1) { ["dividendRate"]=> float(2.52) } } }
And essentially, I want to have the dividend amount displayed instead of the word 'array', next to the symbols, in a table- what am I missing here?
Thanks!
You need to further reference the right array elements to get this value in your loop...
foreach($div as $divi => $value) {
echo '<br/>'. $divi.' : '. $value['stats']['dividendRate'];
}
As you can see from the var_dump, this data is an array of arrays of arrays. When you try to echo an array, it will only output the string 'Array'. Specify the keys of the elements of that array to get to the actual data.
foreach($div as $divi => $value) {
echo $divi . ':' . $value['stats']['dividendRate'];
}
This is data formatted.
array(2) {
["F"]=> array(1) {
["stats"]=> array(1) {
["dividendRate"]=> float(0.13)
}
}
["AAPL"]=> array(1) {
["stats"]=> array(1) {
["dividendRate"]=> float(2.52)
}
}
}
Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);
I hope to give enough information here, but I am confused as to why the foreach loop works, it gets each data and outputs it in an li but I am getting an invalid argument error?
Here is the result of the var_dump
array(1) { ["questions"]=>
array(2) { ["title"]=> string(5) "Keanu" [1]=>
array(1) { ["questionlist"]=> array(2) { [0]=>
array(1) {
["a-question"]=> string(1) "1" } [1]=> array(1) {
["a-question"]=> string(5) "civil" } } } } }
Here is my foreach statement
foreach($questions['questions'] as $key => $value){
foreach($value['questionlist'] as $key => $subquestion){ //line 119
echo '<li>'.$subquestion['a-question'].'</li>';
}
}
$questions is a variable used to get the data from the database like this.
$questions = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1" , ARRAY_A);
The data comes from ajax, I modify the ajax $_POST like this before sending to the database.
// Add modifications
$questions['questions'] = $_POST['questions']['data'];
// DB data
$name = $wpdb->escape($questions['questions']['title']);
$data = $wpdb->escape(json_encode($questions));
Screenshot:
I am not sure why I am getting the invalid argument, I suspect its because the array may not be formatted properly, if you need any more information let me know.
A Solution: Thanks to #didierc
I used his code and modified it a bit to display my data in a loop, basically all I did was add another foreach.
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
// This loops all the ['a-question'] data
echo '<li>''.$value['a-question'].''</li>';
}
}
}
}
Try this:
foreach ($questions['questions'] as $key => $value) {
if (is_array($value) && isset($value[ 'questionlist'])) {
foreach ($value['questionlist'] as $subnum => $subquestion) {
foreach ($subquestion as $qtitle => $qanswer) {
With variable names hopefully explicit enough. That should get you started.
NB: The data is probably easier to understand when formatted as below:
array(1) {
["questions"]=> array(2) {
["title"] => string(5) "Keanu"
[1] => array(1) {
["questionlist"]=> array(2) {
[0]=> array(1) {
["a-question"]=> string(1) "1"
}
[1]=> array(1) {
["a-question"]=> string(5) "civil"
}
}
}
}
}