I am trying to print the contents of a nested array, but it simply returns "Array" as a string yet will not iterate with a foreach loop. The arrays are coming from a mongodb find(). The dataset looks like this:
User
Post_Title
Post_Content[content1,content2,content3]
I am trying to get at the content1,2,3.
My current code looks like this:
$results = $collection->find($query);
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
echo $item;
}
}
All this code does is print the Title, followed by Array ( [0] => Array ), followed by Array.
I feel quite stupid to not figure out something that seems so basic. Most posts on stack overflow refer to multidimensional associative arrays - in this case, the top level array is associative, but the content array is indexed.
I have also tried
foreach ($doc['content'] as $item)
But that gives
Warning: Invalid argument supplied for foreach()
I even tried iterating over the returned array again using a nested foreach, like the following:
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
foreach ($item as $next_item)
{
echo $next_item;
}
echo $item;
}
}
The second foreach failed with an invalid argument..
Any thoughts would be greatly appreciated.
edit: perhaps it has something to do with how I am inserting the data to the DB. That code looks like this
$title = $_POST['list_title'];
$content[] = $_POST['list_content1'];
$content[] = $_POST['list_content2'];
$content[] = $_POST['list_content3'];
$object = new Creation();
$object->owner = "$username";
$object->title = "$title";
$object->content = "$content";
$object->insert();
Is this not the proper way to add an array as a property to a class?
The issue is some of array content is an array while other parts are strings. You should test for the sub content $doc being an array using is_array(). If it is, loop through the $doc like you would any other array, and if it isn't, you can echo the content (may need to test the content type before doing this if you're uncertain as to what content it can be)
The problem is in the code that you are saving data. You should replace the following line
$object->content = "$content";
with
$object->content = $content;
Related
I want to merge array result inside foreach loop. Is there any solution about this or other best way. Thanks in advance.
PHP code
include('Config.php');
$data = json_decode(file_get_contents("php://input"));
foreach($data->dataVal as $key => $value){
echo json_encode($config->query($key,$value));}
//this is the response code above --> how to merge this 2,3 array result into one only
[{"name":"Roi"}][{"name":"Tom"}][{"name":"Chad"}]
//result to be expected like this
[{"name":"Roi","name":"Tom","name":"Chad"}] // this is i want
The nearest you will get is by building up an array of the data in the foreach loop and JSON encoding the result...
$result = array();
foreach($data->dataVal as $key => $value){
$result[] = $config->query($key,$value);
}
echo json_encode($result);
This stops having repeated values for the name.
In your original attempt, you were encoding each row separately, so the JSON was invalid.
I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.
take a look below
$newarray = array(
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
);
foreach($newarray as $item){
$item["total"] = 9;
}
echo "<br>";
print_r($newarray);
The result just give me the original array without the new "total". Why ?
Because $item is not a reference of $newarray[$loop_index]:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.
You could use the for() and loop through like this: see demo.
Note: This goes all the way back to scopes, you should look into that.
I'm trying to parse html content, for the value stored in the name tag.
My current try looks like the following:
function getAuthToken(){
$html = file_get_contents('url');
$values = array();
foreach($html->find('input') as $element)
{
$values[$element->name] = $element->value;
}
print_r($values);
}
What am I doing wrong?
$html in your code is not an object its a string (the results of file_get_contents).
$object->name is a class object
$array[key] is an array element
Neither of these in your code will do what you want to achieve with the result of file_get_contents because your $html var is a string, you need to do some string parsing to get the desired results.
You can check that with:
echo gettype($html);
You can also just echo out $html to find out what the string looks like to give you a better idea of what you are working with, for instance, is there a common character that you can explode the sting with an so getting an array to work with within your foreach.
example:
$newarray = explode('&', $html);
foreach ($newarray as $key => $value) {
//do your thing
}
I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.
Hello I can't figure out how to loop through this json encoded array and for each object, get all its values. I need each value as a variable for itself.
echo json_encode($formulars);
This is what i get when i echo it out
[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}]
I have tried this piece of code and I managed to get out the project_name from the first object and that's it:
foreach ($formulars as $current => $project_name) {
$project_name['project_name'];
}
So is there any way i can get all the variables for each object in my array instead of just the project_name?
Like this:
foreach ($formulars as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
Thanks in advance
Seems like you have an objects inside an array. So you will need to loop through the array and get each object. Just JSON_DECODE your encoded string like below.
Perhaps:
$data = json_decode($formulars,true);
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/
//You should now be able to do this
foreach ($data as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
The reason I loop is because there is a object inside an array(Javascript way I think).
Use json_decode to convert the json object to an array; then use foreach to loop through the array. That should work.
<?php
$arr_json = json_decode($formulars);
foreach($arr_json as $key => $value)
//Code to perform required actions
?>
This should give you some ideas.
Use json_decode (with TRUE for getting an associative array)to convert your JSON object to an associative array. After that, you can use a foreach loop to traverse through your multidimensional array and print the required values.
Code:
$json = json_decode($string, true);
foreach ($json as $key => $value) {
foreach($value as $key2 => $value2) {
echo $value2."\n";
}
}
Working Demo!