foreach to get the array index results in PHP - php

I got the following parameters as a response from SOAP client. But i only want few to show as a result. I am getting the results properly but its only for 1 vehicle and i have more than 1 vehicles. So i dont know how to loop to get the results.
Output for 1 vehicle
array (size=5)
'SchwackeCode' => int 10130969
'WE_Number' => int 19373134
'HSN' => string '0005' (length=4)
'TSN' => string 'AMP' (length=3)
'VIN' => string '12345678901472583' (length=17)
Code:
$client = new SoapClient($wsdl, $options);
$result = $client->getVehicleValuation($params);
$return = array(
'SchwackeCode' => $result->vehicle->SchwackeCode,
'WE_Number' => $result->vehicle->WE_Number,
'HSN' => $result->vehicle->HSN,
'TSN' => $result->vehicle->TSN,
'VIN' => $result->vehicle->Ident_Number,
'WE_Number' => $result->vehicle->WE_Number
);
return $return;

ok, then just try this simple code,
$cnt=0;
$arr=Array('SchwackeCode','WE_Number','HSN','TSN' );
foreach($result->Vehicle[$cnt]->Customer[0] as $key=>$val)
{
if(in_array($key,$arr)
{
your_piece of code;
}
$cnt++;
}
Didnt tested this code, but hopefully it will work. :)

Related

Extract just the strings from an array_column array return

I've got told many times, if there is a new question even on the same code to just create a new thread so here I am. Thanks to the guys for helping me with the previous question.
I have the following code:
/* Return an array of _octopus_ids */
$offices = array_map(
function($post) {
return array(
'id' => get_post_meta($post->ID, '_octopus_id', true),
);
},
$query->posts
);
/* Dump out all the multi-dimensional arrays */
var_dump($offices);
$test = array_column($offices, 'id');
var_dump($test);
var_dump($offices) dumps the following:
array (size=10)
0 =>
array (size=1)
'id' => string '1382' (length=4)
1 =>
array (size=1)
'id' => string '1330' (length=4)
var_dump($test) dumps the following:
array (size=10)
0 => string '1382' (length=4)
1 => string '1330' (length=4)
Problem:
How can I use the following code:
$results = $octopus->get_all('employees/' . $test; which results in an Notice: Array to string conversion error.
I want to be able to make a results call such as this $results = $octopus->get_all('employees/1382'); - So I want just the numeric string of $test to be appended to the end of employees/
If I hardcode the 1382 after employees/, I get the following result:
object(stdClass)[1325]
public 'id' => int 1382
What's the proper way to array of strings into just strings?

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'];

Change element of loop

I have an php array like this (var_dump)
I need change one of it's element
array (size=204)
'Address' =>
array (size=3)
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
'CityDistrict' =>
array (size=3)
0 => string 'return $this->hasOne(CityDistrict::className(), ['id' => 'cityDistrictId']);' (length=76)
1 => string 'CityDistrict' (length=12)
2 => boolean false
'Contacts' =>
array (size=3)
0 => string 'return $this->hasMany(Contact::className(), ['addressId' => 'id']);'
1 => string 'Contact' (length=7)
2 => boolean true
'City' =>
array (size=3)
'Addresses' =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'Region' =>
array (size=3)
0 => string 'return $this->hasOne(Region::className(), ['id' => 'regionId']);' (length=64)
1 => string 'Region' (length=6)
2 => boolean false
'CityDistricts' =>
array (size=3)
0 => string 'return $this->hasMany(CityDistrict::className(), ['cityId' => 'id']);'
1 => string 'CityDistrict' (length=12)
2 => boolean true
'CityDistrict' =>
array (size=2)
Addresses =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityDistrictId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
How can i change value 'CityDistrict' in this loop? or 'Addresses'? using php foreach
My code doesn't work please help understand what wrong!
private static function checkExistClass($relations)
{
foreach ($relations as $name => $relation) {
foreach ($relation as $functionName => $functionValue) {
$functionNameGet = 'get' . $functionName;
$directory = new Model;
if (method_exists($directory, $functionNameGet)) {
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
}
}
}
return $relations;
}
I interprete your question that you want to rename the array index Addresses to NewAddresses:
$relations['CityDistrict']['NewAddresses'] = $relations['CityDistrict']['Addresses'];
unset($relations['CityDistrict']['Addresses']);
EDIT:
to do that in your foreach loop, change:
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
to:
$relations[$name]['funky_key_'.$functionName] = $functionValue;
unset($relations[$name][$functionName]);
maybe this is what you're looking
if (isset($array['n'])) {
$array['name'] = $array['n'];
unset($array['n']);
}
you can see the complete post in Change key in associative array in PHP
see you!
PD Sorry, for my english is not the best
Your loop seems wrong. In the outer loop, $name assumes values such as 'Address', and $relation is an array such as { 'City' => ..., 'CityDistrict' => ... }.
So in the second loop $functionName assumes values such as City, CityDistrict and Contacts.
If you want to change that, you need to do something like #hellcode suggested:
if ('CityDistrict' == $functionName) {
$relations[$name]['NewDistrict'] = $relations[$name][$functionName];
unset($relations[$name][$functionName]);
continue;
}
This looks like a Laravel/Eloquent problem to me. If you can state more precisely what it is that you're trying to accomplish, possibly someone could be of more use.
Also, you seem to want to create a function given its code in a string. To do this you would need create_function (or declare the function as anonymous/lambda function):
$code = "return 42;";
$array['function'] = create_function('', $code);
print $array['function']();
Note that the use of create_function is somewhat deprecated. Also you need a PHP > 5.3+ (or 5.4+ if you go lambda and require $this).

php json_decode return [object Object]

I have a problem with JSON data in PHP. I need to use data from this JSON in my SQL statement. When I'm trying to debug it with echo(var_dump, or print_r is not working too) command the output with is
{"records":"tekst","name":"[object Object]"}
This is a JSON structre:
{
records: 'tekst',
name: {
imie: 'imie1',
nazwisko: 'nazwisko1'
}
}
I'm trying to decode this by json_decode(), but I have an error
"Warning: json_decode() expects parameter 1 to be string, array
given".
Does anyone know what's wrong?
PHP manual about JSON and the format required: function.json-decode. basically, double quotes only and names must be quoted.
a demonstration of conversion using PHP.
So, you supply the json string that looks like, with the whitespace removed, like this:
{records:[{id:1,name:'n1'},{id:2,name:'n2'}]}
Which is an object containing an array with two entries that could be arrays or objects.
Except, it is not a valid JSON string as it contains single quotes. And PHP wants all the names in double quotes, as in "id":1.
So, possible PHP code to recreate that, assuming arrays as the inner entries is:
$json = new stdClass();
$records = array();
$entry = array('id' => 1, 'name' => 'n1');
$records[] = $entry;
$entry = array('id' => 2, 'name' => 'n2');
$records[] = $entry;
$json->records = $records;
$jsonEncoded = json_encode($json);
Which, when 'dump'ed looks like:
object(stdClass)[1]
public 'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
Now, the string that structure produces is:
{"records":[{"id":1,"name":"n1"},{"id":2,"name":"n2"}]}
Which looks similar to yours but is not quite the same. Note the names in double quotes.
However, if your json string looked the same then PHP could decode it, as is shown below:
$jsonDecoded = json_decode($jsonEncoded);
var_dump($jsonDecoded, 'decoded');
Output: Note all objects...
object(stdClass)[2]
public 'records' =>
array
0 =>
object(stdClass)[3]
public 'id' => int 1
public 'name' => string 'n1' (length=2)
1 =>
object(stdClass)[4]
public 'id' => int 2
public 'name' => string 'n2' (length=2)
We may want arrays instead so use the true as the second parameter in the 'decode'
$jsonDecoded = json_decode($jsonEncoded, true);
var_dump($jsonDecoded, 'decoded with true switch');
Output: with arrays rather than objects.
array
'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
string 'decoded with true switch' (length=24)

Accessing JSON object with PHP, Random Object Name

I am trying to parse out certain things within the JSON code, but the problem is that the two groups of arrays that have the information in it I need have random names, here is from the var_dump:
array (size=2)
'results' =>
array (size=1)
0 => string 'Phone.5d5b6fef-a2e0-4b08-cfe3-bc7128b776c3.Durable' (length=50)
'dictionary' =>
array (size=3)
'Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral' =>
array (size=8)
'id' =>
array (size=5)
...
'type' => null
'names' =>
array (size=1)
...
'age_range' => null
'locations' => null
'phones' =>
array (size=1)
...
'best_name' => string 'John Smith' (length=15)
'best_location' => null
'Location.28dc9041-a0ee-4613-a3b0-65839aa461da.Durable' =>
array (size=30)
'id' =>
array (size=5)
...
'type' => string 'ZipPlus4' (length=8)
'valid_for' => null
'legal_entities_at' => null
'city' => string 'City' (length=8)
'postal_code' => string '12345' (length=5)
'zip4' => string '4812' (length=4)
'state_code' => string 'MO' (length=2)
'country_code' => string 'US' (length=2)
'address' => string 'Main St, City, MO 12345-4812' (length=33)
'house' => null
No I am trying to get best_name from under the part that starts with Person and address under Location. But when I do:
$string = file_get_contents($url);
$json=json_decode($string,true);
var_dump($json);
echo $json['dictionary']['Person']['best_name'];
I get Undefined index: Person error, because the actual object name for Person is:
Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral which is different every time I do a search. Is there a way to do this without putting the random generated line in?
Hopefully this makes sense, thanks for the help in advance!
If the Person key always starts with the string "Person", than simply do a foreach and check the key which contains this string.
Like:
foreach ($json['dictionary'] as $key => $value) {
if (preg_match('/^Person/', $key)) {
echo $json['dictionary'][$key]['best_name'];
}
}
Of course this get complicated, if you have multiple keys which start with "Person".
You can do the same with "Location" or any other string you need.
How about something like this ... loop through $json['dictionary']'s index keys to find something that starts with "Person".
$foundIt = false;
foreach (array_keys($json['dictionary']) as $key) {
if (substr($key,0,6) == 'Person') {
$foundIt = $key;
break;
}
}
if ($foundIt) { echo $json['dictionary'][$foundIt]['best_name']; }

Categories