Retrive answer_id in php - php

Below are my database value and i want to retrieve answer_id using php.
a:1:{i:0;O:8:\"stdClass\":7:{s:11:\"question_id\";s:1:\"1\";s:13:\"question_text\";s:18:\"This is question 1\";s:9:\"answer_id\";s:1:\"2\";s:11:\"answer_text\";s:4:\"asss\";s:11:\"points_base\";s:1:\"2\";s:6:\"points\";s:1:\"2\";s:15:\"custom_response\";s:0:\"\";}}

Try below code, it will return answer id to you.
$str = "a:1:{i:0;O:8:\"stdClass\":7:{s:11:\"question_id\";s:1:\"1\";s:13:\"question_text\";s:18:\"This is question 1\";s:9:\"answer_id\";s:1:\"2\";s:11:\"answer_text\";s:4:\"asss\";s:11:\"points_base\";s:1:\"2\";s:6:\"points\";s:1:\"2\";s:15:\"custom_response\";s:0:\"\";}}";
$arry = unserialize($str);
echo $arry[0]->answer_id;

The Issues is that your serialized String contains back-slashes which would mess with the serialized object. Solution: Remove the backslashes and unserialzed the string and you'd get your object back:
<?php
$strSerializedWithSlashes = 'a:1:{i:0;O:8:\"stdClass\":7:{s:11:\"question_id\";s:1:\"1\";s:13:\"question_text\";s:18:\"This is question 1\";s:9:\"answer_id\";s:1:\"2\";s:11:\"answer_text\";s:4:\"asss\";s:11:\"points_base\";s:1:\"2\";s:6:\"points\";s:1:\"2\";s:15:\"custom_response\";s:0:\"\";}}';
$strSerializedWithoutSlashes = str_replace("\\", "", $strSerializedWithSlashes);
$objUnSerialized = unserialize($strSerializedWithoutSlashes);
var_dump($objUnSerialized);
// DUMPS::
array (size=1)
0 =>
object(stdClass)[1]
public 'question_id' => string '1' (length=1)
public 'question_text' => string 'This is question 1' (length=18)
public 'answer_id' => string '2' (length=1)
public 'answer_text' => string 'asss' (length=4)
public 'points_base' => string '2' (length=1)
public 'points' => string '2' (length=1)
public 'custom_response' => string '' (length=0)
You can test it here: https://eval.in/571535
And now; to get you answer_id You can simply do this:
<?php
$objData = $objUnSerialized[0];
$answerID = $objData->answer_id;
var_dump($answerID); // DUMPS: '2'

Related

Unable To Show Data in PHP Using ASP.NET Web Service

I've created a simple web service in ASP.NET and want that service to be consumed in a PHP application. The web service is as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<Customer> GetCustomers(int id)
{
id = Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);
List<Customer> lst = null;
using (var context = new DemoEntities())
{
lst = (from c in context.Customer
where c.CustomerID == id
select c).ToList();
}
return lst;
}
In the above web service, a customer id is passed to retrieve customer details. So to consume this service in PHP, I've tried to do the following using nuSoap library as follows and it works almost:
<?php
require_once("lib/nusoap.php"); //Using the nuSoap library
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE); //Passed the ASP.NET web service and an object created
$result = $client->call('GetCustomers', array('id' => 1)); //Called the GetCustomers method and passed a default parameter
foreach($result as $item) //Tried to iterate in a foreach loop
{
echo $item; //Here is the issue - The output returns or returned only the name 'Array'
}
?>
I've done PHP programming a long time ago and trying to figure the issue searching google. I've even tried to access the array index with the web service property directly like the below but seems like missing something or may be not the correct way: Any idea would be appreciated
echo $item[1]->CustName;
echo $item[1]; //Even this
Right now, I am getting the Xml data as follows using the Soap web service:
<ArrayOfCustomer>
<Customer>
<CustomerID>2</CustomerID>
<CustName>John</CustName>
<CustAddress>On Earth</CustAddress>
<CustLocation>On Earth</CustLocation>
<CustSex>Male</CustSex>
<CustType>3</CustType>
<CustStatus>2</CustStatus>
<CustDetails>Great guy - Always regular.</CustDetails>
</Customer>
</ArrayOfCustomer>
Update 1: Used var_dump($item) and currently getting the array elements as follows:
array
'Customer' =>
array
'CustomerID' => string '2' (length=1)
'CustName' => string 'John' (length=7)
'CustAddress' => string 'On Earth' (length=25)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Great guy - Always regular.' (length=47)
But when tried with this $item->Customer->CustName, getting this error again - Trying to get property of non-object.
Update 2: Again used var_dump($item) and the result is as follows with PHP programming:
<?php
require_once("lib/nusoap.php");
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
$result = $client->call('GetAllCustomers'); //Without any parameter
foreach($result as $item)
{
echo var_dump($item);
}
?>
Output:
array
'Customer' =>
array
0 =>
array
'CustomerID' => string '1' (length=1)
'CustName' => string 'Jack' (length=7)
'CustAddress' => string 'On Earth' (length=25)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Regular Customer and always happy to cooperate.' (length=47)
1 =>
array
'CustomerID' => string '2' (length=1)
'CustName' => string 'John' (length=4)
'CustAddress' => string 'On Earth' (length=7)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Great guy - Always regular.' (length=25)
Again, tried to use two loops to get the values that's as follows but it only returns first two results and there are total 10 records in the database:
<?php
require_once("lib/nusoap.php");
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
$result = $client->call('GetAllCustomers');
$count = count($result);
foreach($result as $item)
{
for($i = 0; $i <= $count; $i++)
{
echo 'Name: ' . $item['Customer'][$i]['CustName'].'<br/>';
}
}
?>
Output:
Name: Jack //Returns only first two records though it should return all the records
Name: John
Simply do a var_dump($item); in php to see how they array structure is.. currently I do not know what the response object is, but for example you can access the keys as such: echo $item->Customer->CustName;
If it is an array response, not an object, then: $item['Customer']['CustName'];

How to loop over an array and conditionally update a nested value

I have two arrays like:
array (size=4)
0 => string '5' (length=1)
1 => string '4' (length=1)
2 => string '2' (length=1)
3 => string '2' (length=1)
3 => string '8' (length=1)
and one array more that I load from an XML file:
object(SimpleXMLElement)[1]
public 'book' =>
array (size=101)
0 =>
object(SimpleXMLElement)[2]
public 'id' => string '1' (length=1)
public 'title' => string 'p' (length=1)
1 =>
object(SimpleXMLElement)[3]
public 'id' => string '2' (length=1)
public 'title' => string 'pp' (length=2)
2 =>
object(SimpleXMLElement)[4]
public 'id' => string '3' (length=1)
public 'title' => string 'pen' (length=3)
3 =>
object(SimpleXMLElement)[5]
public 'id' => string '4' (length=1)
public 'title' => string 'lapton' (length=6)
......
......
101 =>
object(SimpleXMLElement)[103]
public 'id' => string '101' (length=1)
public 'title' => string 'title' (length=5)
I want to compare each value of key id of second array with key of first array for each value. When it's the same, I want to update value of key title of second array.
Assuming your first array is $idArray and your second is $xmlArray, you could use something like this.
$result = array_map(function($xmlElement) use ($idArray) {
if (in_array($xmlElement->id, $idArray)) {
$xmlElement->title = 'updated value';
}
return $xmlElement;
}, $xmlArray);
Assumptions
the first array is called $array1
the second array is called $fromXML
the second array is not actually an array, it's a SimpleXMLElement with the following structure (psuedocode / JSONish syntax)
{
'book' => {
0 => SimpleXMLElement {
'id' => 1,
'title' => 'p'
}
}
}
I assume you can access the second array of elements with $fromXML['book']
I assume you can access an attribute of the first element with $fromXML['book'][0]['id']
I assume that you can set the text of the title of the first element with $fromXML['book'][0]['title'][0] = 'new title'
based on How can I set text value of SimpleXmlElement without using its parent? and PHP SimpleXML, how to set attributes? and PHP foreach change original array values
Solution
foreach($fromXML['book'] as $key => $element) {
if(array_key_exists($element['id'], $array1)) {
$fromXML['book'][$key]['title'][0] = $array1[$element->id];
}
}
Caveat and troubleshooting
I didn't test this, just going off of the documentation. If I've misinterpreted the structure of your SimpleXMLElement array, try experimenting with var_dump($fromXML['some']['key']) until you find the right way to access the array/element
Note: Apparently, array_key_exists() performs better than in_array() on large arrays
Try this for now
foreach($array1 as $arr1 => $val1){
foreach($array2 as $arr2 =>$val2){
if($arr1==$arr2){
$val2['title']='update value';
}
}
}

Array merge if key not exists

I tried merging two arrays if the key is not exists in the array but I cannot accomplish this. How can i do? This is what I have tried:
array (size=3) // name of the array $exchange
'purchase' => string '1' (length=1)
'agriculture' => string '1' (length=1)
array (size=6) // name of the array $fixed
'purchase' => string '0' (length=1)
'ICT' => string '0' (length=1)
'agriculture' => string '0' (length=1)
'entertainment' => string '0' (length=1)
'goods and service' => string '0' (length=1)
'other' => string '0' (length=1)
foreach($fixed as $keys=>$values){
if(!in_array($values, $exchange, true)){
array_push($exchange, $keys);
}
}
I get this result:
array (size=7)
'ICT' => string '1' (length=1)
0 => string 'purchase' (length=8)
1 => string 'ICT' (length=3)
2 => string 'agriculture' (length=11)
3 => string 'entertainment' (length=13)
4 => string 'goods and service' (length=17)
5 => string 'other' (length=5)
But I want:
array (size=7)
'ICT' => string '1' (length=1)
'purchase' => string '0' (length=8)
'agriculture' => string '0' (length=11)
'entertainment' => string '0' (length=13)
'goods and service' => string '0' (length=17)
'other' => string '0' (length=5)
Try this:
foreach ($fixed as $keys => $values) {
if (! array_key_exists($keys, $exchange)) {
$exchange[$keys] = $values;
}
}
It checks if the key $keys does not already exists in $exchange and adds it together with its value ($values).
Or you can simply replace the entire foreach() block with:
$exchange = $exchange + $fixed;
The addition $exchange + $fixed adds to $exchange the keys (and their values) that are in $fixed but are not in $exchange. The combined array is then stored in $exchange.
Read also this answer. It explains where your code is wrong.
There's a couple of problems with this:
in_array will search the values of the given array, not the keys, so in this case you just end up checking if the value "0" exists in the array $variable. I assume instead you wanted to check if the key already exists.
array_push pushes a new value into the next available key.
What you need is to check if a key exists, and if not, add it with the existing value. Try this instead:
for($fixed as $key=>$value)
{
if(!isset($exchange[$key])) // Check if the key exists
{
$exchange[$key] = $value; // Add the new key -> value pair.
}
}
Try with array_merge (http://php.net/manual/es/function.array-merge.php)
$result = array_merge($array1, $array2);
You can do it in several ways depending the result you desire:
foreach($fixed as $key=>$values){
if(!isset($exchange[$key])){
$exchange[$key]=values;
}
}
or
$exchange += $fixed;
or
$exchange = array_merge($fixed,$exchange);

converting array to stdClass in CodeIgniter

I am returning data from two tables in CodeIgniter with the function below
public function test()
{
$this->db->select('*');
$this->db->from('WHOUSE1.DLY_BWR_DLY_PERFORMANCE');
$this->db->join('WHOUSE1.DATE_DIM', 'WHOUSE1.DATE_DIM.DATE_KEY = WHOUSE1.DLY_BWR_DLY_PERFORMANCE.BDP_DATE');
$query = $this->db->get();
return $query->result_array();
}
Using var_dump I am getting the result below
array (size=3226)
0 =>
array (size=121)
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
array (size=121)
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
But what I will like to get is this
array (size=3226)
0 =>
object(stdClass)[27]
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
object(stdClass)[29]
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
I can't seem to get a way of converting the array into object(stdClass) Any help will be appreciated as am new to CodeIgniter.
Array to stdClass can be done in php this way.
stdClass:: __set_state(array());
Or a nicer way.
$a = (object) array();
Use this code in Your Model ( change your table name and select, distinct fileds )
$this->db->select('DISTINCT(subcategory)');
$this->db->from('tbl_property');
$this->db->where('status','1');
$data = $this->db->get()->result();
$sub_id = array();
foreach ($data as $row)
{
array_push($sub_id,$row->subcategory);
}
$this->db->from('tbl_subcategory');
$this->db->where_in('id',$sub_id);
$data1 = $this->db->get()->result();
return $data1;
use
return $query->result();
This function returns the query result as an array of objects, or an empty array on failure. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Edit:
If you just want to print you can use var_dump() or print_r().
var_dump($obj);
print_r($obj);
If you want an array of all properties and their values use get_object_vars().
$properties = get_object_vars($obj);
print_r($properties);
According to the same documentation for Codeigniter I detail:
result_array()
This function returns the query result as a pure array, or an empty array when no
result `is produced. Typically you'll use this in a foreach loop, like this:`
and ..
result()
This function returns the query result as an array of objects, or an empty array
on failure.
You should return your data in this way
return $query->result();

multiarray - how to keep first 3 index groups of each source type

I have a multi-array where I need to keep the first 3 index groups and remove the rest from the multiarray (in each group).
See multiarray here: https://gist.github.com/no1uknow/6887497
So:
In this example I need the multi-array to keep: The first 3 Heavy, Lite, Intermediate, etc (these are identified by the source_type_cd)
Example of the Lite part of the array after the first 3 are kept:
0 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '29' (length=2)
'corrective_action_txt' => string 'Repair-Passenger Seat-Loose / Displaced' (length=39)
'rec_count' => string '00050' (length=5)
'group_id' => int 48
1 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '1' (length=1)
'corrective_action_txt' => string 'Repair-Passenger Seat-Inoperative' (length=33)
'rec_count' => string '00047' (length=5)
'group_id' => int 44
2 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '31' (length=2)
'corrective_action_txt' => string 'Repair-Passenger Seat-Worn / Chaffed / Frayed' (length=45)
'rec_count' => string '00042' (length=5)
'group_id' => int 50
You will simply have to loop through the array and look if it has any of those values and place into a new array.
Example (where $arr is your multiarray):
// My silly solution for knowing what to look for
// When one is found, it will be removed from the array.
$find = array('Lite','Lite','Lite','Intermediate','Intermediate','Intermediate','Heavy','Heavy','Heavy');
// New array where your the values you want will be placed in
$new_arr = array();
foreach($arr as $v) {
// No need to keep looking if there's no more to find.
if(empty($find))
break;
// Look in $find array if current "source_type_cd" is still sought-after
$key = array_search($v['source_type_cd'], $find);
if($key !== false) {
$new_arr[] = $v; // Add to new array
unset($find[$key]); // Remove from "find" array
}
}
Thanks Colandus I actually figured it out like this... I was trying to avoid to many loops.
In a loop above this I set the source_type_cd in an array:
$groups[]=$value['source_type_cd']
Next I loop through the array and take the top 3 of each group by using array_splice twice and then merging back into a new array.
(also, I'm using a start and end point ($group_count).)
$start = 0;
$group_count = $i+1;
$top_count = 3;
foreach($groups as $k => $v) {
$top_count_array = array_merge((array)$top_count_array, (array)array_slice(array_slice($sorted_array, $start, $group_count, true),0,$top_count,true));
$start = $start+$group_count;
}
var_dump($top_count_array);
Again appreciate the input. Tried to shorten this code down from so many loops. Also requirements will change for grabbing the amount of $top_count and $group_count... Needed something a little more dynamic. :-)

Categories