I am doing project in laravel. I am fetching a value from database in user1 variable.
foreach($users1 as $us){
$uss[$i] = $us->city_id;
$users2[$i] = DB::table('provider_city')->select('provider_id')->where('city_id','=', $uss[$i])->get();
$i++;
}
return $users2;
when I return user2, I am getting
[[{"provider_id":"14785"}],[{"provider_id":"125478"}]] such values.
I want only values like ['14785','125478'].
I know this may be very simple. Give suggestions.
This can be achieved with json_decode, like so
$json= '[
{
"provider_id": "14785"
},
{
"provider_id": "125478"
}
]';
$jsonDecoded = json_decode($json);
foreach($jsonDecoded as $item)
{
//Do something with it, e.g
echo $item->provider_id;
}
Edit: Upon finding out that this is a multidimensional array
This question here should point you in the right direction.
There's actually an Eloquent method for that - lists():
$users2[$i] = DB::table('provider_city')
->where('city_id','=', $uss[$i])
->lists('provider_id')
->all();
This will give you an array of just the provider ids.
Whether you need the all() call at the end or not depends essentially on what version of Laravel you're using.
Maybe something like
return DB::table('provider_city')
->whereIn('city_id', array_pluck($users1, 'city_id')
->lists('provider_id');
Related
I am working in the PHP language.
The object is
"[{"value":"test_1"},{"value":"test_2"}]"
and I want
['test_1', 'test_2']
Here is my code...
foreach(json_decode($email) as $emails){
$arr[]=$emails->value;
}
$final = json_encode($arr);
The Output is
"["test_1","test_2"]"
I am not satisfied with this output.
If anyone can help me please give an answer.
assuming that You have the data of array of objects like
$array=[
{
"value":"value1"
},
{
"value":"value2"
}
]
simple use the function pluck() to retrieve data as you want .
$value_array=$array->pluck("value");
Your All keys need to be same to retrieve all values
the $value=["value1","value2"]
I am following this documentation
to implement export to Excel in my laravel 4 project.
So am trying to generate excel file from array like this:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
But this raises exception:
Object of class stdClass could not be converted to string
What am I doing wrong ?
UPDATE:
Tried this:
$data = get_object_vars($data);
which results in:
get_object_vars() expects parameter 1 to be object, array given
This:
$data = (array)$data;
Results in the initial error.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
$data is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.
You can either use
get_object_vars()
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';
I have a query in my model using joins and returned the query results as array
result_array();
I then returned that result to my controller where i called the model.
$data = $this->Model->show();
foreach($data as $val)
{
$arr[$val['recipename']] = $val['componentname'];
}
if($data != null)
{
$this->load->view('Admin\success',$arr);
}
I didnt originally had $arr value. I just added it up there to make the array clearer. Anyhow, with or without.
var_dump($data) and var_dump($arr) or even if i $recipename or $componentname stll null.
returns null. says they are undefined.
I don't know what went wrong.
I read this other question. that is why i made the $arr so i could make it a single array and so when it transfers it will be extracted and tried to echo them but to no avail.
Codeigniter passing data from controller to view
EDIT:
query works fine, it returns values.
$sample = $this->db->select('recipe.recipename,component.componentname')->from('recipe')
->join('recipecomponent','recipe.recipeid = recipecomponent.recipeid')
->join('component','component.componentid = recipecomponent.componentid')
->group_by('recipe.recipeid')
->get()
->result_array();
return $sample;
Once you pass an array of data to your view the array keys are turned into variables. Say for example after your foreach loop your $arr variable is an array like this
array [
'cheese' => 'brie'
'cookie' => 'chocolate chips'
]
You would then access $arr['cheese'] by doing the following in the view
echo $cheese;
Trying to access $data or $arr in the view won't work because they are not in scope
$data is most likely empty and you are iterating an empty array.
A simple way to debug is found below:
Debugging an array or object:
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($data, true).'</pre></div>';
or
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($this->Model->show(), true).'</pre></div>';
You should also turn on error reporting in your __construct like so:
error_reporting(E_ALL);
If the print_r() shows you an empty array then your model is returning no data and the answer to your question is probably that you need to fix your query.
{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.
I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/