merge array inside foreach loop - php

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.

Related

Loop through 5 dimensional array in PHP

I have a json response as array
$responseArray['business_discovery']['media']['data'][0]['id']
I'm trying to loop through the 'data' element and grab the value of 'id' and place that into an array like
$idarray[0] = $responseArray['business_discovery']['media']['data'][0]['id']
next iteration
$idarray[1] = $responseArray['business_discovery']['media']['data'][1]['id']
What is the best loop to accomplish this?
You should be able to set data to a variable and loop through that.
$data = $responseArray['business_discovery']['media']['data'];
foreach($data as $item) {
// do something with the id
$thisId = $item['id']
}

How to get properties through loop from a REST JSON response using Httpfull in PHP and how to show in grid

As in the URL, I don't want to give a limit, I want to show in loop
[0]. I don't want to give [0] or [1] etc. I want to do it in a loop.
http://buildout.com/api/v1/d7d8b6a8cbd23c1f69e3a327b32c8217d6bea635/properties.json?limit=2
<?php
$url='my url';
$res = \Httpful\Request::get($url)->expectsJson()->send();
$data = json_decode($res,true);
$name1 = $data['properties'][0]['broker_id']; // I WANT LOOP HERE INSTED OF [0]
echo $city1;
?>
You can loop through the response data dynamically to get each datum without specifying the index as follows:
foreach ($data['properties'] as $key=>$val) {
var_dump($key);
}
The $key can be:
First $data['properties'][0];
Next $data['properties'][1];
and so on...

Display foreach array item one by one in ajax

In PHP I am getting an array from foreach. I am JSON encoding and showing all the results at once. This works fine. But what if I need to display array items one by one as foreach still continues?
<?php
$array = //somearray;
$data_arr = array();
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
echo json_encode(array('success'=>true,'data'=>$data_arr));
//here i can display the data in my jquery using each function
//i can display the whole data at once after the foreach is completed
//what i need is i want to display first element of data_arr after its loop is completed and then the second element and so on
?>
Did you try http://www.php.net/array_shift ? its php function you need to call this function after foreach
<?php
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
print_r array_shift($data_arr);
//Print First array value from this $data_arr list.
?>
Thanks.
What you looking for is Streaming Response.
Checkout following link to learn how to do that.
https://www.sitepoint.com/php-streaming-output-buffering-explained/

json_encode get values foreach object

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!

Printing contents of a nested array

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;

Categories