Related
Hello i want to unserialize an array in order to display the array values.
The way that the array is inserted to my db field is like this.
persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
and the function i have done but i am not getting any results is this
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize(array($feed->persons));
$personsText = " ";
if(!empty($personsArr)){
list($firstItem) = $personsArr;
foreach ($firstItem as $key => $value) {
foreach ($value as $valueInner) {
$personsText .= $valueInner.", ";
}
}
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I am getting nothing on personsText although persons is persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
Any help?
The value in the array is a JSON string, so you need to decode it.
The argument to unserialize() should just be $feed->persons, it shouldn't be in an array.
Instead of the loop, you can use array_column() to get all the value elements, and implode() to combine them with comma delimiters.
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize($feed->persons);
$personsText = " ";
if(!empty($personsArr)){
$firstItem = json_decode($personsArr[0], true);
$personsText = implode(', ', array_column($firstItem, 'value'));
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I am trying to parse a json array string. Though print_r prints all the values properly but while fetching the records I failed.
I must be doing something very terribly wrong. Could you please help to correct it.
So here is my code
<?
$str ='
{
"tenant_view_details": [
{
"status":"S",
"tenant_general":[
{"tenant_id":"6003","code":"ICI001","type":"BANK","category":"SM","gstn":"IWSDFS7372","pan":"KSAH9876AS","cin":"ASHED456","name":"ICICI Bank","address_line_1":"23, Hertz Plaza, Rajiv Chowk","address_line_2":" ","address_city":"New Delhi","address_distict ":"New Delhi","address_state ":"DL","address_state_code ":"07","address_pin ":"119923","contact_name ":"contact_name","contact_phone ":"1234567890","contact_std_code ":"11","contact_landline ":"1234567890","contact_email_id ":"contact#email.com"} ],
"tenant_bank": [
{ "bank_name ":"xyz","bank_account_no ":"12345","account_type ":"abc","ifsc_code ":"xx123","address_line_1 ":"qwer","address_line_2 ":"23","address_city ":"abc","address_district ":"xyz","address_state_name ":"asd","address_state_code ":"02","address_pin ":"123456" } ],
"tenant_agreement": [
{ "category ":"OM","tenancy_type ":"EXT","echarge_type ":"FIX","total_tenancy_value ":"32900.00","energy_charge_value ":"16543.00","rev_share_pct ":"0.05","start_dt":"10-1-2018","end_dt":"31-12-2020","attachment_path ":"na","change_value ":"na","latest_flag ":"Y","w_status ":"20","status ":"ACT"} ],
"tenant_sites": [
{"tenant_id":"6003","site_master_id":"1020","tn_site_code":"UPWMORA00069473","tn_site_name":"Deendayal Nagar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1019","tn_site_code":"UPWGHAZ00069467","tn_site_name":"DJ College Newari Road, Modina","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1018","tn_site_code":"UPWMORA00069464","tn_site_name":"Bazar Makhbra","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1016","tn_site_code":"UPWGHAZ00069454","tn_site_name":"Hoshdarpur Garhi","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1011","tn_site_code":"UPWMUZN00069430","tn_site_name":"Sikanderpur","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1008","tn_site_code":"UPWALIG00069299","tn_site_name":"Mukund Vihar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"} ]
}
]
}
';
$dataset = json_decode($str, true);
//print_r ($dataset);
foreach ($dataset['tenant_view_details'] as $newdata) {
$general = $newdata['tenant_general'];
$bank = $newdata['tenant_bank'];
$agreement = $newdata['tenant_agreement'];
$sites = $newdata['tenant_sites'];
}
//prinitng data
echo "<br/>";
print_r($general);
echo "<br/>";
print_r($bank);
echo "<br/>";
print_r($agreement);
echo "<br/>";
foreach($general as $general_data){
(isset($general_data['tenant_id']) && !empty($general_data['tenant_id']))? $tenant_id=$general_data['tenant_id'] : $tenant_id="not set";
echo "<br/>tenant_id::" . $tenant_id;
}
foreach($bank as $bank_data){
(isset($bank_data['bank_name']) && !empty($bank_data['bank_name']))? $bank_name=$bank_data['bank_name'] : $bank_name="not set";
echo "<br/>bank_name:" . $bank_data['bank_name'];
}
foreach($agreement as $agreement_data){
(isset($agreement_data['category']) && !empty($agreement_data['category']))? $category=$agreement_data['category'] : $category="not set";
(isset($agreement_data['tenancy_type']) && !empty($agreement_data['tenancy_type']))? $tenancy_type=$agreement_data['tenancy_type'] : $tenancy_type="not set";
(isset($agreement_data['echarge_type']) && !empty($agreement_data['echarge_type']))? $echarge_type=$agreement_data['echarge_type'] : $echarge_type="not set";
echo "<br/>category:" . $category;
echo "<br/>tenancy_type:" . $tenancy_type;
echo "<br/>echarge_type:" . $echarge_type;
}
?>
Your problem is that in your $bank and $category arrays, all the keys have trailing spaces on them. If you change the references to include those spaces, your code works fine. See https://3v4l.org/GX5iC
Alternatively you can trim the array keys, using something like this code inside your foreach loops:
$bank_keys = array_map('trim', array_keys($bank_data));
$bank_data = array_combine($bank_keys, array_values($bank_data));
You could also create a recursive function to trim the entire $dataset value. For example:
function trim_keys($array) {
foreach ($array as $key => $value) {
echo "trimming key '$key' to '" . trim($key) . "'\n";
unset($array[$key]);
$array[trim($key)] = $value;
if (is_array($value))
$array[trim($key)] = trim_keys($value);
else
$array[trim($key)] = $value;
}
return $array;
}
Then, by using
$dataset = trim_keys($dataset);
Your code will work fine. Demo on 3v4l.org
I need to modify the data structure of json array list as per some key value using PHP. I am explaining my code below.
<?php
$output=array(
array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA001"
),array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA002"
),array(
"first_name"=>"Rama",
"last_name"=>"Nayidu",
"reg_no"=>13,
"paper_code"=>"BA001"
)
);
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$result[]=array(
"name"=>$value["first_name"].' '.$value['last_name'],
"reg_no"=>$value['reg_no'],
"paper1"=>$value['paper_code'],
"paper2"=>"",
"paper3"=>"",
"paper4"=>""
);
}
}
The output of the input array is given below.
// Output:
[
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA001"
},
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA002"
},
{
"first_name":"Rama",
"last_name":"Nayidu",
"reg_no":13,
"paper_code":"BA001"
}
];
The above is my array list. Here I need to modify the all row value by reg_no means if there are multiple rows including same reg_no then those will merge with joining the both name and my expected output should like below.
expected output:
[
{
'name':"robin sahoo",
"reg_no":12,
"paper1":"BA001",
"paper2":"BA002",
"paper3":"",
"paper4":""
},
{
'name':"Rama Nayidu",
"reg_no":13,
"paper1":"BA001",
"paper2":"",
"paper3":"",
"paper4":""
}
]
Here paper1,paper2,paper3,paper4 will be selected serially means suppose same reg_no=12 has first row paper_code= BA001 then it will be paper1=BA001 and second row paper_code=BA002 then it will be paper2=BA002 and so on. Here I am using PHP to map this array.
Try the following, Let me know..
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
$temp=array();
if(!empty($output)){
foreach ($output as $key => $value) {
if(isset($temp[$value['reg_no']])){
if(empty($temp[$value['reg_no']]["paper1"]) || $temp[$value['reg_no']]["paper1"] == ""){
$temp[$value['reg_no']]["paper1"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper2"]) || $temp[$value['reg_no']]["paper2"] == ""){
$temp[$value['reg_no']]["paper2"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper3"]) || $temp[$value['reg_no']]["paper3"] == ""){
$temp[$value['reg_no']]["paper3"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper4"]) || $temp[$value['reg_no']]["paper4"] == ""){
$temp[$value['reg_no']]["paper4"] = $value['paper_code'];
}
}else{
$temp[$value['reg_no']] = array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}
}
if(!empty($temp)){
foreach ($temp as $key => $value) {
$result[] = $value;
}
}
This Code May help you
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$output[$key]=array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}echo "<pre>";print_r($output);
?>
You can try with this
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'name' => $name,
'reg_no' => $value['reg_no'],
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'];
}
$result = array_values($result); // reindex result array
$result = json_encode($result); // Encode to json format
print_r($result); // print result
This assumes that first_name and last_name is always same for each reg_no
$Product = array("aaa","bbb","ccc");
$suppliername = array("S0001","S0002","S0001");
$vals = array_count_values($suppliername);
print_r($suppliername);
print_r($vals);
foreach($Product as $index => $value)
{
if($vals[$index]>1)
{
echo $suppliername[$index]."+++"."Multiple Entries";
// Here i have to get S0001
}
else
{
echo $suppliername[$index]."+++"."Single Entry";
// Here i have to get S0002
}
}
how to pass $index to array value? I am trying to check value of the index is greater than or not in if condition. How to get this?
With your code now it couldn't work since your print_r($val) result was :
Array
(
[S0001] => 2
[S0002] => 1
)
The key of your $vals are the result of your $suppliername array, so try like this maybe :
$Product = array("aaa","bbb","ccc");
$suppliername = array("S0001","S0002","S0001");
$vals = array_count_values($suppliername);
print_r($suppliername);
print_r($vals);
foreach($Product as $index => $value)
{
if($vals[$suppliername[$index]]>1)
{
echo $suppliername[$index]."+++"."Multiple Entries";
}
else
{
echo $suppliername[$index]."+++"."Single Entry";
}
}
The result :
S0001+++Multiple Entries
S0002+++Single Entry
S0001+++Multiple Entries
Is this what you are looking for?
I'm not sure i understood well what you wanted, but here it does what you want as result :
<?php
$Product = array("aaa","bbb","ccc");
$suppliername = array("S0001","S0002","S0001");
$vals = array_count_values($suppliername);
echo "<pre>";
var_dump($suppliername);
echo "</pre>";
echo "<pre>";
var_dump($vals);
echo "</pre>";
foreach($Product as $index => $value)
{
if($index>1)
{
echo "<br />" . $suppliername[$index]."+++"."Multiple Entries";
// Here i have to get S0001
}
else
{
echo "<br />" . $suppliername[$index]."+++"."Single Entry";
// Here i have to get S0002
}
}
Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;