How to loop(foreach) json decoded in php (laravel) - php

This is my code`
$a =json_decode($user->name, true);
And I need to loop $a, but I'm getting
"Invalid Argument supplied for foreach"
while executing
`

you can loop in array and i think the result of this $a =json_decode($user->name, true);
is string

Based on what you've posted in the other answer and the comment to me, you need to change your loop to this:
foreach($a[0] as $akey => $aloop) { array_push($array, $aloop->email)); }
Notice the change from $a to $a[0]

You should describe to us how your JSON String look like.
Maybe you can try this code below :
$user= '[{"name":"Jonathan Suh","email":"jonathan.suh#gmail.com"},
{"name":"William Phil","email":"will.phil#gmail.com"},
{"name":"Allison Kin","email":"allison.kin#gmail.com"}]';
// Replace with your own JSON
$a = json_decode($user, true); // Array
// Create empty array to hold query results
$array = [];
// Begin loop ( foreach )
foreach ($a as $akey => $aloop) {
array_push($array, ['name' => $aloop["name"], 'email' => $aloop["email"]]);
}
// Encode your array result from Loop Process to JSON
// You can change whatever you want to do from your Result Loop
$jsonENC = json_encode($array);
// You know what is this...
echo $jsonENC;

Related

PHP - Merge append multiple json arrays

I need to merge/join multiple json string that contains arrays (which also need to be merged) but I don't know what is the best way to achieve this :
Initial array of json strings (called $rrDatas in my example below):
Array
(
[0] => {"asset":[1],"person":[1]}
[1] => {"asset":[2]}
)
Expected result :
{"asset":[1,2],"person":[1]}
The main difficulty is that the number of arrays is undefined (my example is made with 2 arrays but it could be 3,4 etc.). The second difficulty is that there can be multiple properties (like "asset", "person" etc. however always arrays). These possible properties are known but are many so it would be better if the algorithm is dynamic.
What I am able to do at the moment :
$mergedAssets['asset'] = [];
foreach ($rrDatas as $rrData)
{
$rrDataJson = \GuzzleHttp\json_decode($rrData, true);
$mergedAssets['asset'] = array_merge($mergedAssets['asset'],$rrDataJson['asset']);
}
$result = \GuzzleHttp\json_encode($mergedAssets, true);
Result :
{"asset":[1,2]}
This works well but this is not dynamic, should I duplicate this part for each possible properties (i.e. "person", etc.) ?
Thanks,
Guillaume
Edit : Brett Gregson's and krylov123's answers below helped me build my own solution which is a mix between both suggestion:
$mergedJson = [];
foreach ($rrDatas as $rrData)
{
$rrDataJson = \GuzzleHttp\json_decode($rrData, true);
foreach(array_keys($rrDataJson) as $property)
{
$mergedJson[$property] = array_merge($mergedJson[$property] ?? [], $rrDataJson[$property]);
}
}
return \GuzzleHttp\json_encode($mergedJson, true);
Find below a better example :
$rrDatas = Array (
[0] => {"asset":[1,2],"person":[1],"passive":[1]}
[1] => {"asset":[3],"charge":[1],"passive":[2]}
)
Which must result in :
{"asset":[1,2,3],"person":[1],"passive":[1,2],"charge":[1]}
Edit 2 : I have just tried Progrock's solution and it seems to work perfectly as well : https://3v4l.org/7hSqi
You can use something like:
$output = []; // Prepare empty output
foreach($rrDatas as $inner){
foreach($inner as $key => $value){
$output[$key][] = $value;
}
}
echo json_encode($output); // {"asset":[1,2],"person":[1]}
Which should give you the desired output. This should work regardless of the keys within the individual arrays and even with empty arrays.
Working example here
Another example with more arrays and more keys and empty arrays
<?php
$array =
[
'{"asset":[1],"person":[1]}',
'{"asset":[2]}',
];
$array = array_map(function($v) { return json_decode($v, true);}, $array);
$merged = array_merge_recursive(...$array);
print json_encode($merged);
Output:
{"asset":[1,2],"person":[1]}
You need to use foreach ($array as $key => $value) iteration, to be able to dynamicaly use keys of your json array (e.g. "asset" and "person").
Solution:
$mergedAssets['asset'] = [];
foreach ($rrDatas as $key => $value)
{
$rrDataJson = \GuzzleHttp\json_decode($value, true);
$mergedAssets[$key] = array_merge($mergedAssets[$key],$rrDataJson[$key]);
}
$result = \GuzzleHttp\json_encode($mergedAssets, true);

array_merge function doesn't work properly in Laravel

In my project i'm split an array index value based on regex value. but when i want merge all array together the merge function doesn't merge.
Here is my code sample.
$testarray=array();
$merge_array=array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
print_r(array_merge($merge_array,$testarray));
}
The print_r show this result.
Array ( [0] => Admin [1] => Manager ) Array ( [0] => User [1] => Test )
You just merge arrays, but don't assign results to any variable, proper code is:
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
// here you add $testarray values to
// `$merge_array` on each iteration
$merge_array = array_merge($merge_array,$testarray);
}
// print result array after loop
print_r($merge_array);
The Laravel framework has nothing to do with your issue. You're using PHP's standard functions.
The array_merge function doesn't modify the array you provide to it but provides the resulting array as its output. So you should assign array_merge's result to $merge_array.
Please try the following code:
$testarray = array();
$merge_array = array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray = preg_split("/[##%$|:\s,]+/",$value);
}
$merge_array = array_merge($merge_array, $testarray);
}
print_r($merge_array);
You seem to think wrong.
print_r(array_merge($merge_array,$testarray));
The above line is in "foreach" loop.
In that case, to get a merged result, you should do like the followings;
$merge_array = array_merge($merge_array,$testarray)
In your code, $merge_array remains empty, so you see the current result.

PHP foreach insert array

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.

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!

Filling the array value if it is missing in the assoc array?

Filling the array value if it is missing in the assoc array?
I have an :
$A= array("A1"=>array("a"=>1,"b"=>2,"d"=>3),
"A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
);
base on the A["A2"] size is bigger than A["A1"]
I want got the new $A look like this
$A= array("A1"=>array("a"=>1,"b"=>2,"c"=>"0.00","d"=>3),
"A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
);
i'd do it this way:
if (count($A['A2']) > count($A['A1'])){
foreach($A['A2'] as $key => $value){
if (!array_key_exists($key, $A['A1'])){
$A['A1'][$key] = '0.00';
}
}
}

Categories