How can i remove value from object - php

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"]

Related

JSON into PHP: access array data if each array has a different name

I am trying to access data from a JSON file, using PHP.
Here is what the JSON feed looks like:
[{
"performancesByDateDisplay":{
"2021-09-02":[{
"performanceId":10813388,
"performanceTime":"8:00 PM"
}],
"2021-09-03":[{
"performanceId":10813638,
"performanceTime":"8:00 PM"
}]
}
}]
And here is the code I am using to access the data:
foreach($json_output->performancesByDateDisplay as $events) {
$perfId = $events->performanceId;
}
But $perfId is not returning any value. I think it's because each array has a different "name" (for example "2021-09-02" in the first instance)? How do I access the data, without knowing in advance what this name will be (it's coming from an external json feed)?
Thanks!
Both the root of your JSON and each "$events" item is an array of objects, not just an object.
If you were to iterate each of these arrays for example, and access the objects inside one-by-one, you'd get the expected result:
foreach($json_output as $json_output_item){
foreach($json_output_item->performancesByDateDisplay as $events){
foreach($events as $event){
$perfId = $event->performanceId;
var_dump($perfId);
}
}
}
Output:
int(10813388)
int(10813638)
Did you forget to decode?
Well, first you need to decode the JSON data into a native PHP structure.
$decodedJson = json_decode($json_output, true);
Then you can access it just how you'll access a native PHP array and associative array. Notice the true, that's to decode the JSON string into an associative array. Also, it'd be better to just get inside the array while decoding, hence making the above statement:
$decodedJson = json_decode($json_output, true)[0];
Now you can iterate over it.
foreach($decodedJson as $events) {
foreach($events as $date => $event) {
$perfId = $event[0]['performanceId'];
}
}

How to get only array values from multi dimentional array

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');

Get a specific recurring value from JSON array using PHP foreach loop

I have the following JSON array:
{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}
Using PHP is it possible to display a specific recurring value, for example if I wanted to display "key1" in a foreach loop it would return the following:
Example1
Example5
Example9
Appreciate any tips on what to use to do this, thanks.
You aren't going to be able to do this using json_encode because it's not valid JSON. (Keyspace collision)
You are going to need to assemble the object manually.
You might consider creating the individual items, then using implode(). Then you can prepend and append { and }.
<?php
$jsonObject='{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}';
$jsonArray = array_map(
function($array){
$keyValue=explode(":",$array);
return array("key"=>substr($keyValue[0],1,-1),"value"=>substr($keyValue[1],1,-1));
},
explode(
",",
substr($jsonObject,1,-1)
)
);
foreach($jsonArray as $object){
$output[$object['key']][]=$object['value'];
}
echo implode("\n",$output['key1']);
?>

json decode to php variable example needed

Hi I have the following field which is saved as a field called attachment.
[
{
"name":"ClientFiles\/POL02, Impartiality Policy Statement,Rev0_wg1t36oh.pdf",
"usrName":"POL02, Impartiality Policy Statement,Rev0.pdf",
"size":172223,
"type":"application\/pdf",
"searchStr":"POL02, Impartiality Policy Statement, Rev0.pdf,!:sStrEnd"
}
]
Could someone please tell me how I would write a json_decode code in order to save an element from it as a variable.
for example:
$seachStr = json_decode[attachment->"searchStr"]
Thanks.
$attachmentArr = json_decode($attachment,true); // convert the json to php array variable
echo '<pre>', var_dump($attachmentArr), '</pre>';// OUTPUT
$searchStr = $attachmentArr['searchStr'];// Pick the desired element out of the array
echo '<pre>', var_dump($searchStr), '</pre>';// OUTPUT

json encoding 2 dimension array

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/

Categories