I've tried to look up the clue, still not able to solve it though.
I have json like this, and I need it to store in db the following 'id', 'n', 'ct'. But the element "rep" has various numbering. Can anyone help me to create the code "foreach" to be able to call it and then save it?
Basically I need to get result for each "rep" with its "id"
Such as:
rep1 - id 1,2,4,5
rep2 - id 1,2
{ "dataFlags": 8192,
"totalItemsCount": 6,
"indexFrom": 0,
"indexTo": 0,
"items": [{
"rep": {
"1": {
"id": 1,
"n": "volvo",
"ct": "avl_unit_group",
"c": 54071
},
"2": {
"id": 2,
"n": "bmw",
"ct": "avl_unit_group",
"c": 59631
},
"4": {
"id": 4,
"n": "audi",
"ct": "avl_unit_group",
"c": 27264
},
"5": {
"id": 5,
"n": "mercedes",
"ct": "avl_unit",
"c": 18276
}}},
{"rep": {
"1": {
"id": 1,
"n": "tesla",
"ct": "avl_unit",
"c": 24132
},
"2": {
"id": 2,
"n": "scania",
"ct": "avl_unit",
"c": 2178
}},
"repmax": 0
}]}
this code is written in php.
$rep1="";
foreach ($row['item'] as $key => $value) {
$rep1 .=$value->id.'-';
}
$rep1=substr($rep1, 0, -1);
the output will be $rep1= 1-2-4-5
Your JSON data:
$jsonData = '{
"dataFlags": 8192,
"totalItemsCount": 6,
"indexFrom": 0,
"indexTo": 0,
"items": [{
"rep": {
"1": {
"id": 1,
"n": "volvo",
"ct": "avl_unit_group",
"c": 54071
},......
}},
{"rep": {
"1": {
"id": 1,
"n": "tesla",
"ct": "avl_unit",
"c": 24132
},..........
},
"repmax": 0
}]}';
Try below code. it's working. I have used 2 foreach for store your JSON data in the database.
$jsonData = json_decode($jsonData,true);
foreach($jsonData['items'] as $items){
foreach($items['rep'] as $rep){
$sql = "INSERT INTO MyGuests (id, n, ct) VALUES (".$rep['id'].",".$rep['n'].",".$rep['ct'].")";
$conn->query($sql)
}
}
Get result for each "rep" with its "id":
$jsonData = json_decode($jsonData,true);
$allRep = [];
foreach($jsonData['items'] as $items){
$tmpRep = [];
foreach($items['rep'] as $key => $rep){
$tmpRep [] = $key;
}
$allRep[] = implode(', ',$tmpRep);
}
echo "<pre>";
print_r($allRep);
Output:
Array
(
[0] => 1, 2, 4, 5
[1] => 1, 2
)
Check this:
$arr = json_decode($yourJSONstring);
foreach($arr->items as $index=>$rep){
foreach($rep->rep as $element){
$reps[$index][] = $element->id;
}
}
Reps array will look like:
Array (
[0] => Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )
[1] => Array ( [0] => 1 [1] => 2 )
)
So you can easily convert it to string format as you desire.
Related
I wanna know how to iterate an array to count elements in PHP, I've trying next,
foreach ($items as $item) {
$tm[$item->provider->name] = [];
foreach ($items as $item) {
$tm[$item->provider->name][$item->product->brand->name] = isset($tm[$item->provider->name][$item->product->brand->name]) ? $tm[$item->provider->name][$item->product->brand->name] + 1 : $tm[$item->provider->name][$item->product->brand->name] = 1;
}
}
But I get a wrong result, I get an array but I get a very high number count as if iterated many timesmany times
The structure of the array is as follows
[{
"id": 1,
"product": {
"id": 1,
"brand": {
"id": 1,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 2,
"product": {
"id": 2,
"brand": {
"id": 2,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "at&t"
}
},
{
"id": 3,
"product": {
"id": 3,
"brand": {
"id": 3,
"name": "iphone"
}
},
"provider": {
"id": 1,
"name": "t-mobile"
}
}]
IIUC, you are trying to count the product->brand->name values for each provider->name. You can do that using this code:
$tm = array();
foreach ($items as $item) {
$product = $item->product->brand->name;
$provider = $item->provider->name;
$tm[$provider][$product] = ($tm[$provider][$product] ?? 0) + 1;
}
print_r($tm);
Output (for your sample data):
Array
(
[at&t] => Array
(
[iphone] => 2
)
[t-mobile] => Array
(
[iphone] => 1
)
)
Demo on 3v4l.org
From your code example you apparently want to count how many occurrences are for each "thing" in your array, otherwise count() would have probably sufficed...
Though you are doing a lot of work to pre-init the counting array - that is completely unneeded: read about auto-vivifcation.
Code like so would probably suffice (I'm not following your example code here - you'd need to work out to your needs):
$counters = [];
foreach ($items as $item)
#$counters[$item->name][$item->model]++;
I have question, is it possible not to duplicate the array object by looping on it? Right now I used laravel as my backend
I have here my response which is the exchange object duplicate itself.
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
]
Now my goal is to push the exchange without duplication:
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
}
]
Here is what my foreach loop like and how i push the array object.
$myArray = [];
foreach($exchange_check as $primary_array) {
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
array_push($myArray, (object)[
'exchange' => $primary_array,
'exchange_list' => $second_array,
]);
}
}
}
Thanks
You should add exchange data to array only once in first loop:
$myArray = [];
foreach($exchange_check as $primary_array) {
$idx = array_push($myArray, ['exchange' => $primary_array]);
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
//array_push() returns the new number of elements in the array,
//to get currently added array element we should subtract 1 from this number
$myArray[$idx-1]['exchange_list'][] = $second_array;
}
}
}
And in second loop add only exchange_list data to array.
I get back the data from DB with php, and I get it back as follows so I want to modify it.
This what I tried:
$result = $db->run("SELECT * FROM.....")->fetchAll();
foreach($result as $key => $val) {
$result[$key] = $result[$key]['id'];
}
I want to change the key ( 0, 1) to the id values (5, 6) Change this:
{
"0": {
"id": 5,
"date_created": "2021-08-18 03:35:31",
"status": 1
},
"1": {
"id": 6,
"date_created": "2021-08-18 03:35:55",
"status": 1
}
}
To this:
{
"5": {
"id": 5,
"date_created": "2021-08-18 03:35:31",
"status": 1
},
"6": {
"id": 6,
"date_created": "2021-08-18 03:35:55",
"status": 1
}
}
try this
$newResult = [];
foreach($result as $key => $val) {
$newResult[$val['id']] = $val;
}
print_r($newResult);
i have a nested json array of objects:
$json_url_data = [{
"form_name": "z1",
"name":"name1",
"children": [{
"form_name": "z2",
"name":"name2",
"children": [{
"form_name": "z3",
"name":"name2"
}]
}]
}]
i want to dynamically insert a new key value pair, which should look some thing like this:
[{
"form_name": "z1",
"name":"name1",
"peopleCount": "125,678,190",
"children": [{
"form_name": "z2",
"name":"name2",
"peopleCount": "156,987",
"children": [{
"form_name": "z3",
"name":"name2",
"peopleCount": "678,098"
}]
}]
}]
And i tried using recursion like below, but wasnt able to achieve the above result:
function print_data($menu, $depth) {
foreach ($menu as $value) {
$deepid = '\"'.$value['form_name'].'\"';
$api_call_var = '{{i have a apiu call proxy here}}';
$read_data = file_get_contents($read_data);
$read_data = json_decode($read_data, true);
$value['peopleCount'] = $read_data['count']; // after decode read the count
$obj_array[] = $value;
if (is_array($value['children'])) {
print_data ($value['children'],$depth+1);
}
}//end of for each
}//end of function
print_data ($json_url_data, 0);
i am stuck for hours, any help will be really appreciated.
This should solve your issue. When updating same array, you need to receive parameters as reference and update the same array in recursion.
Here is the code. I've added 123 as peopleCount but you add value using the API call.
<?php
echo "<pre>";
$json_url_data = json_decode('[{
"form_name": "z1",
"name":"name1",
"children": [{
"form_name": "z2",
"name":"name2",
"children": [{
"form_name": "z3",
"name":"name2"
}]
}]
}]', true);
function print_data(&$menu) {
foreach($menu as &$value) {
$value['peopleCount'] = 123; // using some API call add peopleCount value here
if(isset($value['children'])) {
print_data($value['children']);
}
}
return $menu;
}
print_r(print_data($json_url_data));
And this is the output.
Array
(
[0] => Array
(
[form_name] => z1
[name] => name1
[children] => Array
(
[0] => Array
(
[form_name] => z2
[name] => name2
[children] => Array
(
[0] => Array
(
[form_name] => z3
[name] => name2
[peopleCount] => 123
)
)
[peopleCount] => 123
)
)
[peopleCount] => 123
)
)
$arr = json_decode('[{
"form_name": "z1",
"name":"name1",
"peopleCount": "125,678,190",
"children": [{
"form_name": "z2",
"name":"name2",
"peopleCount": "156,987",
"children": [{
"form_name": "z3",
"name":"name2",
"peopleCount": "678,098"
}]
}]
}]', TRUE);
function countTotal($data) {
if(is_array($data)){
foreach($data as $row){
$row['peopleCount'] = 0;///here total val
if(isset($row['children']) {
countTotal($row['children']);
}
}
}
else {
$data['peopleCount'] = 0;//here total val
}
}
countTotal(&$arr);
I have two JSON arrays with some values. I need to merge those values in a format using PHP. Here is the array format and the output format that I needed:
Array 1:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}
Array 2:
{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}
Expected Result after merge:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
},
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
Thank you.
Try this code
<?php
$json1 = '{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}';
$json2 = '{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}';
// Decode json into array
$jArray1 = json_decode($json1, true);
$jArray2 = json_decode($json2, true);
// Merging array
$merge['data'] = $jArray1['data'] + $jArray2['data'];
// Encoding array to json
$mergedJson = json_encode($merge);
print_r( $mergedJson );
?>
$de_json = json_decode('{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}}', True);
echo '<pre>';print_r($de_json);
You will get this output
Array
(
[data] => Array
(
[1] => Array
(
[id] => 1
[name] => red
)
[25] => Array
(
[id] => 3
[name] => green
)
)
)
the convert other two json array to php array and
use array_merge() to get the merged array.