I'm trying to test each 'voucher' in a multi-dimensional array and I was advised that the best way to do this is the foreach loop. However, I'm not sure how to use $key and $value in order to access the vouchers.
This is how the array looks like : https://imgur.com/a/VXjJ4lG
foreach($allVouchers as $key => $value){
$signIn = curl_init();
$voucherURL = 'https://splash-static.ironwifi.com/radius_test.php?ip=' . $ip . '&backup_ip=' . $backupIP . '&auth_port=' . $port . '&secret=' . $secret . '&username=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&password=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&c=*cachebuster*&nas_ip=19.29.39.49';
curl_setopt($signIn, CURLOPT_RETURNTRANSFER, true);
curl_setopt($signIn, CURLOPT_URL, $voucherURL);
$access = curl_exec($signIn);
curl_close($signIn);
$accessArray = json_decode($access, true);
print_r($accessArray);
}
This is the output of var_dump:
array(
9
) {
[0]=> array(
6
) {
[\"_links\"]=> array(
4
) {
[\"self\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=1\" }
[\"first\"]=> array(
1
) {
[\"href\"]=> string(
63
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers\" }
[\"last\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=9\" }
[\"next\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=2\" } }
[\"_embedded\"]=> array(
1
) {
[\"vouchers\"]=> array(
25
) {
[0]=> array(
8
) {
[\"id\"]=> string(
32
) \"secret id\"
[\"code\"]=> string(
7
) \"mntvre7\"
[\"username\"]=> string(
7
Here I think is a similar minimal data structure that is equivalent to yours:
<?php
$data =
[
[
'_links' =>
[
],
'_embedded' =>
[
'vouchers' =>
[
[
'code' => 23
],
[
'code' => 47
]
]
]
]
];
foreach($data as $item) {
foreach($item['_embedded']['vouchers'] as $voucher) {
echo $voucher['code'], "\n";
}
}
Output:
23
47
Related
I want to echo each persona included in the array $personas.
The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").
Any help is much appreciated :)
<?php
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
foreach ( $person as $inner_param => $inner_value ) {
echo $param . ": " . $value . "<br>";
}
};
?>
Desired result:
Name: John | Age: 30 | Nationality: Spain |
Name: Mike | Age: 45 | Nationality: Peru |
Try this;
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
$text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}
I believe that I fixed it. Should it be as follows? Any better option?
foreach ($personas as $persona ) {
echo "<br>";
foreach ( $persona as $param => $value ) {
echo $param . ": " . $value . " | ";
}
};
Here are list of arrays which i echoed in
Array
(
[CustomerID] => manish14
[TicketID] => 45691
[TicketNumber] => 1045828
[CustomerUserID] =>
)
Array
(
[CustomerID] => ghisingraaz#gmail.com
[TicketID] => 45686
[TicketNumber] => 1045823
[CustomerUserID] => ghisingraaz#gmail.com
)
Array
(
[CustomerID] => ranjana#classic.com.np
[TicketID] => 45661
[TicketNumber] => 1045798
[CustomerUserID] => ranjana#classic.com.np
)
........
........
........
I want to display customerID , TicketID and TicketNumber of each array in a table format. How can i retrieve those values. I have this in multiple foreach loop thats why i am having problem getting those values.
Here is my code incase anyone wants to see. phpfiddle.org/main/code/wb4u-nrsj
You can find my code in this PhpFiddle.
<?PHP
error_reporting(0);
//////// OTRS specific information ////////
$url = "https://otrs.classic.com.np/otrs/rpc.pl"; //// URL for OTRS server
$username = "ctdeveloper"; //// SOAP username set in sysconfig
$password = "ctdeveloper"; //// SOAP password set in sysconfig
$TicketID = $_GET['id'];
########################################################################
#### You don't have to change anything below here, although you can ####
########################################################################
#### Initialize new client session ####
echo "<table><tr><th>CustomerID</th><th>TicketID</th><th>TicketNumber</th></tr>";
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => "Core",
'trace' => 1,
'login' => $username,
'password' => $password,
'style' => SOAP_RPC,
'use' => SOAP_ENCODED
)
);
#### Initialize new client session ####
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => "Core",
'trace' => 1,
'login' => $username,
'password' => $password,
'style' => SOAP_RPC,
'use' => SOAP_ENCODED
)
);
$queues = array(1 => "Postmaster",
2 => "Raw",
3 => "Junk",
4 => "Retail Support",
5 => "Enterprise Support",
6 => "Sales",
7 => "Marketing",
8 => "Fiber Survey",
9 => "Fiber Support",
10 => "Billing",
11 => "NOC",
12 => "Wireless Support",
13 => "Core-Tasks",
14 => "Chitwan",
15 => "Developer",
16 => "Operations",
17 => "Administration",
18 => "Hetauda",
19 => "Business",
20 => "Info",
21 => "Corporate",
22 => "Wireless Survey",
23 => "Recovery",
24 => "L2-Support",
);
foreach ($queues as $queue_number => $queue_name) {
#### Create and send the SOAP Function Call ####
$TicketDetail_search = $client->__soapCall("Dispatch",
array($username, $password,
"TicketObject", "TicketSearch",
"Result", "ARRAY",
"UserID", 1,
"QueueIDs", array($queue_number),
"StateType", "open"
));
// REMOVE s-gensym
$ticketInfo = array();
if ($TicketDetail_search) {
foreach ($TicketDetail_search as $name => $value){
if (false !== strpos($name, "s-gensym"))
{
$ticketInfo[] = $value;
}
}
}
foreach($ticketInfo as $TicketID)
{
$TicketDetail_get = $client->__soapCall("Dispatch",
array($username, $password,
"TicketObject", "TicketGet",
"TicketID", $TicketID,
));
foreach($TicketDetail_get as $t)
{
$ticketInfo1 = array();
$i = 0;
foreach ($TicketDetail_get as $name => $value){ // explode the xml response
if (false !== strpos($name, "s-gensym")){
$temp[$i] = $value;
if($i > 0) {
$v = $temp[$i-1];
if($i % 2 != 0){
$ticketInfo1[$v] = $value;
}
}
$i++;
}
}
}
echo "<tr>";
echo "<td>" . $ticketInfo1['CustomerID'] . "</td>";
echo "<td>" . $ticketInfo1['TicketID'] . "</td>";
echo "<td>" . $ticketInfo1['TicketNumber'] . "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
Is this what you are looking for ?
How can i merge array with the same value?
I have three array which are $participants, $conferance_participants and $contacts
i want to compare values with this three array and merge
for example :
if $participants['calleridnum'] == $conferance_participants['uid'] == $contacts['name']
i want the output to be like this :
Array
(
[0] => Array
(
[calleridnum] => 1
[test] => yay
[uid] => 1
[channel] => deze
[name] => 1
[limit] => 1
)
)
this is my code so far:
<?php
$participants = [
[ 'calleridnum' => 1,
'test' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'test' => 'yay2',
'channel' => 'deze'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$c) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $c['uid']) && ($c['uid'] == $cs['name'])) {
foreach ( $c as $key=>$val ) {
if (!isset($p[$key])) {
$participants[$participant][$key] = $val;
}
}
}
}
}
}
print_r( $participants );
?>
Try to call array_merge() , but you still have to consider the different values with the same key (eg. the values of key 'test' )
if (($p['calleridnum'] == $c['uid']) && ($p['uid'] == $c['name'])) {
$participants[$participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
}
The following is my code which adds documents and fires a query using Solr.
It's showing an error:
SolrInputDocument number 1 is not a valid SolrInputDocument instance
Catchable fatal error: Argument 1 passed to SolrClient::query() must be an instance of SolrParams, string given in /var/www/ps/test.php on line 85
<?php
require_once( 'bootstrap.php' );
$options = array( 'hostname' => SOLR_SERVER_HOSTNAME );
$client = new SolrClient($options);
// Create two documents to represent two auto parts.
$parts = array(
'spark_plug' => array(
'partno' => 1,
'name' => 'Spark plug',
'model' => array( 'Boxster', '924' ),
'year' => array( 1999, 2000 ),
'price' => 25.00,
'inStock' => true,
),
'windshield' => array(
'partno' => 2,
'name' => 'Windshield',
'model' => '911',
'year' => array( 1999, 2000 ),
'price' => 15.00,
'inStock' => false,
)
);
$documents = array();
foreach ( $parts as $item => $fields ) {
$part = new SolrDocument();
foreach ( $fields as $key => $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $datum ) {
$part->addField( $key, $datum );
}
}
else {
$part->$key = $value;
}
}
$documents[] = $part;
}
// Load the documents into the index
try {
$client->addDocuments( $documents );
$client->commit();
$client->optimize();
}
catch ( Exception $e ) {
echo $e->getMessage();
}
// Run some queries.
$offset = 0;
$limit = 10;
$queries = array(
'partno: 1 OR partno: 2',
'model: Boxster',
'name: plug'
);
foreach ( $queries as $query ) {
$queryResponse = $client->query($query);
if ( $queryResponse->getHttpStatus() == 200 ) {
// print_r( $response->getRawResponse() );
if ( $queryResponse->response->numFound > 0 ) {
echo "$query <br />";
foreach ( $queryResponse->response->docs as $doc ) {
echo "$doc->partno $doc->name <br />";
}
echo '<br />';
}
}
else {
echo $queryResponse->getHttpStatusMessage();
}
}
?>
I have a working MongoDB aggregate query which I can run via the MongoDB shell. However, I am trying to convert it to work with the official PHP Mongo driver (http://php.net/manual/en/mongocollection.aggregate.php).
Here is the working raw MongoDB query:
db.executions.aggregate( [
{ $project : { day : { $dayOfYear : "$executed" } } },
{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }
] )
Here is my attempt (not working) in PHP using the Mongo driver:
$result = $c->aggregate(array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
'$sort' => array(
'_id' => 1
),
'$limit' => 14
));
The error from the above PHP code is:
{"errmsg":"exception: wrong type for field (pipeline) 3 != 4","code":13111,"ok":0}
Any ideas? Thanks.
The parameter in your Javascript is an array of 4 objects with one element each, in your PHP it's an associative array (object) with 4 elements. This would represent your Javascript:
$result = $c->aggregate(array(
array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
),
array(
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
),
array(
'$sort' => array(
'_id' => 1
),
),
array(
'$limit' => 14
)
));
In addition, if you have at least PHP5.4, you can use simpler array syntax. Transformation to PHP is then trivial, you simply replace curly braces with square brackets and colons with arrows:
$result = $c->aggregate([
[ '$project' => [ 'day' => ['$dayOfYear' => '$executed'] ] ],
[ '$group' => ['_id' => ['day' => '$day'], 'n' => ['$sum' => 1] ] ],
[ '$sort' => ['_id' => 1] ],
[ '$limit' => 14 ]
]);
You can also use the JSON array directly:
$json = [
'{ $project : { day : { $dayOfYear : "$executed" } } },
{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
];
$pipeline = [];
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
You can also use combination like this:
use function MongoDB\BSON\toRelaxedExtendedJSON;
use function MongoDB\BSON\fromPHP;
use function MongoDB\BSON\toPHP;
use function MongoDB\BSON\fromJSON;
$operator = '$dayOfYear';
$json = [];
array_push($json, toRelaxedExtendedJSON(fromPHP(
array('$project ' => array('day' => array($operator => '$executed')))
)));
array_push($json,
'{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
);
$pipeline = [];
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
or
$operator = '$dayOfYear';
$json = [];
array_push($json,
'{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
);
$pipeline = [];
array_push($pipeline, array('$project ' => array('day' => array($operator => '$executed'))));
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
If your aggregation query is dynamic or based on user-input be aware of NoSQL-Injection!
https://www.acunetix.com/blog/web-security-zone/nosql-injections/