PHP Merge two arrays to combine to get expected o/p - php

I have an array with values
[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]
and i have another array
[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]
I need an array of values with two arrays match with its id .
expected output
[{
"": "",
"Gender":"male"
"Age": "27"
}, {
"": "",
"Gender": "female",
"Age": "26",
"Address Line": "japan"
}]
can anyone help to get the expected output.

Please try below solution
$json = '[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]';
$jsondec = json_decode($json,true);
foreach ($jsondec as $key => $value) {
$newjson[$value['id']] = $value['pf_label'];
}
$json2 = '[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]';
$jsondec2 = json_decode($json2,true);
foreach ($jsondec2 as $key => $value) {
foreach ($value as $key => $value) {
$newary[$newjson[$key]] = $value;
}
$finalary[] = $newary;
}
$result = json_encode($finalary);
Hope this will help you!

You can try this!
<?php
$jsonString1 = '[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]';
$jsonString2 = '[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]';
$array1 = json_decode($jsonString1, true);
$indexes = array();
foreach ($array1 as $element) {
$indexes[$element['id']] = $element['pf_label'];
}
$array2 = json_decode($jsonString2, true);
foreach ($array2 as $element) {
foreach ($element as $key => $value) {
if ($key) {
$singleElement[$indexes[$key]] = $value;
} else {
$singleElement[""] = "";
}
}
$result[] = $singleElement;
}
var_dump($result);
Demo

Related

php foreach nested loop retrieve all records

$json_string = '{
"response_code": 200,
"info": {
"days": [
{
"code": "A",
"runs": "111"
},
{
"code": "B",
"runs": "222"
},
{
"code": "C",
"runs": "333"
}
],
"name": "SUPER MARIO",
"number": "010203",
"classes": [
{
"points": "6523",
"name": "ABC",
"available": "N"
},
{
"points": "4253",
"name": "XYZ",
"available": "N"
},
{
"points": "2323",
"name": "JOHN",
"available": "N"
},
{
"points": "5236",
"name": "TAMIL",
"available": "N"
}
]
}
}';
$jsondata = $json_string;
$arr = json_decode($jsondata, true);
foreach($arr as $k=>$v)
{
echo $k."<br>";
}
it prints
response_code
info
But, I need the results like this
6523 ABC
4253 XYZ
2323 JOHN
5326 TAMIL
I have tried and achieved this above results using this below code. But, I want to do it using foreach loop. How do list out all information using foreach?
echo "".$arr['info']['classes'][0]['points']." ".$arr['info']['classes'][0]['name']."<br/>";
echo "".$arr['info']['classes'][1]['points']." ".$arr['info']['classes'][1]['name']."<br/>";
echo "".$arr['info']['classes'][2]['points']." ".$arr['info']['classes'][2]['name']."<br/>";
echo "".$arr['info']['classes'][3]['points']." ".$arr['info']['classes'][3]['name']."<br/>";
You should foreach your array key
foreach($arr['info']['classes'] as $k=>$v)
{
echo $v['points']." " . $v['name']."<br>";
}

Arrange JSON data saving duplicates into one row

Good morning guys!
I'm having a hard time trying to figure out how to arrange the following JSON:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
Into this:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology", "Bachelor in Sociology",
"Number": "53","109",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}]
}
Basically, put the same degrees in one place and have all the names of said degree separated by a comma
I already have this JSON decoded into a variable:
$data = json_decode($topDegrees[1]["diplomas"],true);
Thanks in advance for your help!
I came up with this
$json = <<<JSON
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
JSON;
$data = json_decode( $json, true );
$degrees = $data['degrees'];
$names = array_column($degrees, 'degree');
$count = array_count_values($names);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
foreach ( array_flip($duplicates) as $degree ) {
$filter = array_filter($degrees, function($var) use ($degree) {
return ( $var['degree'] === $degree );
});
$names = [];
$numers = [];
foreach ( $filter as $item ) {
$names[] = $item['Name'];
$numbers[] = $item['Number'];
}
$indices = array_keys($filter);
$index = array_shift($indices);
$degrees[$index]['Name'] = $names; // = join(', ', $names);
$degrees[$index]['Number'] = $numbers; // = join(', ', $numbers);
while ( count($indices) ) {
unset($degrees[array_shift($indices)]);
}
}
$data['degrees'] = $degrees;
print_r(json_encode($data));
// {"showElement":"1","degrees":[{"Name":["Bachelor in Psychology","Bachelor in Sociology"],"Number":["53","109"],"degree":"Bachelor's Degree"},{"Name":"Certificate","Number":"56","degree":"Certificate"},{"Name":"High School Diploma","Number":"28","degree":"High School"}]}
Your wanted json output is not valid, i have made an array structure in its place. If you want comma separated text, just use the join statements I've commented out.
$str = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor\'s Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor\'s Degree"
}]
}';
$str_arr = json_decode($str);
foreach($str_arr->degrees as $k=>$val){
if($val->degree == 'Bachelor\'s Degree'){
$new['Bachelor'][] = $val;
}else{
$new[] = $val;
}
}
foreach($new['Bachelor'] as $aa){
$nameStr[]= $aa->Name;
$numStr[] = $aa->Number;
}
$nameStr = implode(', ', $nameStr);
$numStr = implode(', ', $numStr);
$degree = 'Bachelor\'s Degree';
$new[] = (object) array($nameStr, $numStr, $degree);
unset($new['Bachelor']);
echo $json = json_encode($new);
echo "<pre>"; print_r(json_decode($json));
Hope this helps.
Demo here
This should do it:
<?php
$json = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelors Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelors Degree"
}]
}';
$items = json_decode($json, true);
$orderedItems = [];
$final = ['showElement' => 1];
foreach ($items['degrees'] as $item) {
$orderedItems[$item['degree']]['Name'][] = $item['Name'];
$orderedItems[$item['degree']]['Number'][] = $item['Number'];
$orderedItems[$item['degree']]['degree'] = $item['degree'];
}
foreach ($orderedItems as $order) {
$order['Name'] = (count($order['Name']) > 1) ? $order['Name'] : $order['Name'][0];
$order['Number'] = (count($order['Number']) > 1) ? $order['Number'] : $order['Number'][0];
$final['degrees'][] = [
'Name' => $order['Name'],
'Number' => $order['Number'],
'degree' => $order['degree']
];
}
echo json_encode($final);

How can I access index with # in json

I need to get properties from this "#attributes"
{
"#attributes": {
"docid": "1082530207018916577"
},
"track": [
{
"#attributes": {
"id": "0",
"name": "",
"lang_code": "da",
"lang_original": "Dansk",
"lang_translated": "Danish"
}
},
{
"#attributes": {
"id": "5",
"name": "",
"lang_code": "nl-BE",
"lang_original": "Nederlands (België)",
"lang_translated": "Dutch (Belgium)"
}
},
{
"#attributes": {
"id": "2",
"name": "",
"lang_code": "en-GB",
"lang_original": "English (United Kingdom)",
"lang_translated": "English (United Kingdom)",
"lang_default": "true"
}
},
{
"#attributes": {
"id": "1",
"name": "",
"lang_code": "de-DE",
"lang_original": "Deutsch (Deutschland)",
"lang_translated": "German (Germany)"
}
},
{
"#attributes": {
"id": "4",
"name": "",
"lang_code": "id",
"lang_original": "Indonesia",
"lang_translated": "Indonesian"
}
},
{
"#attributes": {
"id": "6",
"name": "",
"lang_code": "pl",
"lang_original": "Polski",
"lang_translated": "Polish"
}
},
{
"#attributes": {
"id": "7",
"name": "",
"lang_code": "pt-BR",
"lang_original": "Português (Brasil)",
"lang_translated": "Portuguese (Brazil)"
}
},
{
"#attributes": {
"id": "3",
"name": "",
"lang_code": "es-419",
"lang_original": "Español (Latinoamérica)",
"lang_translated": "Spanish (Latin America)"
}
},
{
"#attributes": {
"id": "8",
"name": "",
"lang_code": "sv",
"lang_original": "Svenska",
"lang_translated": "Swedish"
}
}
]
}
My code:
$xml = simplexml_load_file('http://video.google.com/timedtext?type=list&v='.$video->id_youtube);
$json = json_encode($xml);
$result_array = json_decode($json, TRUE);
$res = "";
foreach ($result_array['track']['#attributes'] as $track) {
$res .= $track['lang_code'].'<br>';
}
return $res;
PHP or maybe Laravel is not recognizing the index "#attributes", reporting:
Undefined index: #attributes
How can I get the lang_codes?
$result_array['track'] is an array of objects.
You have to do
foreach($result_array['track'] as $track) {
$track = (array)$track;
$res .= $track['#attributes']['lang_code'].'<br>';
}

php json_encode formatting results?

I have:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
Which returns:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
But I need it to return as:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
To work with the select2 JQuery plugin, I'm working with.
the 'children' name doesn't matter, I think that's just a placeholder so it gets parsed correctly. I'm not sure how I would go about it, I've been trying str_replace() but even that hasn't been working out so great.
I would to it in 2 loops. The first one to group results by category, the 2nd one to format it to fit your needs:
$temp = array();
foreach($all as $array){
if (!isset($temp[$array['cat']])) {
$temp[$array['cat']] = array();
}
$temp[$array['cat']][] = array('id'=>$array['id'], 'type'=>$array['type']);
}
$result = array();
foreach ($temp as $key=>$value) {
$result[] = array('text'=>$key, 'children'=>$value);
}
echo json_encode($result);
This produces the following output:
[{"text":"Main","children":[{"id":1,"type":"Name0"},{"id":2,"type":"Name1"},{"id":3,"type":"Name3"},{"id":4,"type":"Name4"}]},{"text":"Secondary","children":[{"id":5,"type":"Name5"},{"id":6,"type":"Name6"},{"id":7,"type":"Name7"}]},{"text":"Other","children":[{"id":8,"type":"Name8"},{"id":9,"type":"Name9"},{"id":10,"type":"Name10"},{"id":11,"type":"Name11"}]}]

JSON decoding array

I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );

Categories