Merge a Php array into a Php object - php

I need to merge a php array INTO a php object.
I need my php object to look like this :
{"info1":"value","concurrents":[{"concurrent1":"value"},{"concurent2":"value"}],"info3":"value"};
, I'm actually getting my initial object like this :
$initial = pg_fetch_object($result);
After that, I'm getting the array with this command :
$concurrents = pg_fetch_all($result);
So please, how could i merge $concurrents INSIDE my $initial object, for executing this finally for destination to the front end:
print_r(json_encode($initial));
I've tried a foreach, but it doesn't work.

Have you tried the following?
$initial->concurrents = $concurrents;
Or even:
$initial->concurrents = pg_fetch_all($result);

Don't get your initial result as an object, get it as an array:
$initial = pg_fetch_assoc($result);
Then 'merging' is fairly easy (push the initial on to the beginning of your concurrents array):
$concurrents = pg_fetch_all($result);
array_unshift($concurrents, $initial);
Now you can print them:
print_r(json_encode($concurrents));

Related

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

push an array in to multi dimensional array in php issue

I have multidimensional array like this:
$comp = [{"d":1},{"v":9}];
I need to insert another array
$arr = array("s" => 5 );
I tried the following code
$comp [] = array_push($comp,$arr);
I get the output $comp = [{"d":1},{"v":9},{"s":5},3]
I dont need 3.
So I have tried
$comp [] = json_encode(array_push(json_decode($comp),$arr));
But now it shows error.
Plz help me. I am using angular js with php.
You don't need array_push here. Just assign $arr to $comp[]
$comp[] = $arr;
Actually what you did here, let me explain it to you:
$comp[] - means pushback element.
It works the same way here as array_push($comp,$arr), but that function also returns the position where that push happened.
So you are pushing result of pushing the element as well as element itself :)
what you need is
$comp[] = $arr;
OR
array_push($comp,$arr);

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

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/

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

Categories