How can i get the value of a multi array.
So i need out of my array the [user_login] and i the [ID]
So something like echo $array[user_login] where [ID] is $variable[ID]
I need a solution which works without using echo $array[0][user_login]
Array
(
[0] => stdClass Object
(
[ID] => 15
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[1] => stdClass Object
(
[ID] => 28
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[2] => stdClass Object
(
[ID] => 13
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[3] => stdClass Object
(
[ID] => 11
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
)
You could loop through that array to create a new one:
$newArray = array();
foreach($array as $item){
$newArray[$item->ID] = $item;
}
Then with that you can access things using $newArray[$id]->whateveritem;
That's an array of objects, which is a bit different than an array of arrays (or multidimensional array).
You can loop through the array until you find the correct ID and then grab the user_login. SOmething like this
$myID = 15; //Id to search for
foreach ($array as $obj) {
if($obj->ID === $myID) {
echo $obj->user_login; //Or do something with it
}
}
Items in an array of objects are referenced like $object->member. An easy way to search through this array would be a simple foreach() loop. For example, to find the user with id 28, you would do:
foreach($array as $item) {
if ($item->ID == '28') {
echo 'Login is: ' . $item->user_login;
break;
}
}
Edit: Oops, Trivie beat me to it
Related
I'm trying to update an object of a JSON array, I created a function in the name of AlertJSON with 3 params $item and $key and also $newValue, basically the function should first search in the JSON array for the Object that contains the specific value Item in the defined Key and then change the value to $newValue, in the MySQL statement I used JSON_EXTRACT to EXTRACT the object and then apply some changes on the key-value and update the database with the new JSONarray, but I guess I'm wrong using JSON_EXTRACT first I thought JSON_SEARCH will be useful but I tried to understand it and I couldn't figure it out with it, I jumped to EXTRACT function because I think I understand it enough.
here is what I have tried:-
AlertJSON function
<?PHP
public function AlterJSON($item,$key,$newValue){
if($this->connected === true){
try{
$JsonItems = $this->connection->prepare("SELECT `items` FROM `bills` WHERE JSON_EXTRACT(items, '$[*]') = :item");
$JsonItems->bindParam(":item",$item);
$JsonItems->execute();
$JSONfetch = $JsonItems->fetchColumn();
$itemsArray = json_decode($JSONfetch);
foreach($itemsArray as $Array){
$Array[$key] == $newValue;
$newArray = json_encode($Array);
}
return $newArray;
}
catch(PDOException $e){
if($this->errors === true){
return $this->error($e->getMessage());
}else{
return false;
}
}
}
}
?>
Method Call
<?PHP
$db = new dbConnect('connection');
$newCall = $db->AlterJSON('fsdfds','name','tst');
print_r(var_dump($newCall));
?>
I get Invalid argument supplied for foreach() and the var_dump NULL
updated: The Array format:-
Array (
[0] => stdClass Object (
[0] => 1
[1] => o4
[2] => Efexor
[3] => Eklil
[4] => 1
[5] => 30
[6] => 15
[7] => Phezer
[8] => Venlafaxine
[9] =>
[10] => 0
[11] => 2020-03-25
[12] => 2021-08-25
[13] => 1
[14] => 0
[15] => 0
[16] => caps
[17] => ..\upload\Efexor.jpg
[id] => 1
[qty] => 15
[Sale] => 1
[name] => Efexor
[bonus] => 0
[price] => 30
[company] => Phezer
[draftid] => 1
[discount] => 0
[imageurl] => ..\upload\Efexor.jpg
[owned-com] => Eklil
[pack-size] => 0
[codenumber] => o4
[chemicalcom] => Venlafaxine
[dosage-form] => caps
[concentration] =>
[expiration-date] => 2021-08-25
[production-date] => 2020-03-25
)
[1] => stdClass Object (
[0] => 2
[1] =>
[2] => Efexor
[3] => Eklil
[4] => 1
[5] => 15
....etc
I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}
I need help printing the contents of this function:
which came from:
http://drupalcontrib.org/api/drupal/contributions%21flag%21flag.module/function/flag_get_user_flags/7
$userFlags = flag_get_user_flags('user', null, $node->uid, null, false);
If I use print_r:
print '<pre>';
print_r(flag_get_user_flags('user', null, $node->uid, null, false));
print '</pre>';
I get -
Array
(
[follow] => Array
(
[13] => stdClass Object
(
[flagging_id] => 20
[fid] => 5
[entity_type] => user
[entity_id] => 13
[uid] => 1
[sid] => 0
[timestamp] => 1385845849
)
[15] => stdClass Object
(
[flagging_id] => 21
[fid] => 5
[entity_type] => user
[entity_id] => 15
[uid] => 1
[sid] => 0
[timestamp] => 1385912237
)
[17] => stdClass Object
(
[flagging_id] => 22
[fid] => 5
[entity_type] => user
[entity_id] => 17
[uid] => 1
[sid] => 0
[timestamp] => 1386040495
)
[18] => stdClass Object
(
[flagging_id] => 23
[fid] => 5
[entity_type] => user
[entity_id] => 18
[uid] => 1
[sid] => 0
[timestamp] => 1386040515
)
[21] => stdClass Object
(
[flagging_id] => 24
[fid] => 5
[entity_type] => user
[entity_id] => 21
[uid] => 1
[sid] => 0
[timestamp] => 1386043939
)
[14] => stdClass Object
(
[flagging_id] => 25
[fid] => 5
[entity_type] => user
[entity_id] => 14
[uid] => 1
[sid] => 0
[timestamp] => 1386129658
)
)
)
When I use:
foreach($userFlags as $item) {
echo $item;
}
All i get is the word "Array" printed. If your familiar with drupal ideally I need to convert each entity_id to its author. printing the 13,15 etc. is a good start for me.
thanks for any help-
You have an array in an array. Pull the inner array out before your foreach:
$follow = $userFlags['follow'];
foreach($follow as $item) {
echo $item->entity_id;
}
Or more succinctly:
foreach($userFlags['follow'] as $item) {
echo $item->entity_id;
}
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT. There are 2 Patameters 1.$data - It can be Array or String 2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can write like this..
$userFlags = flag_get_user_flags('user', null, $node->uid, null, false);
foreach($userFlags as $item) {
p($item['id']); // If it is array
p($item->id); // If it is an Object
// To get benefit of this code Use above function of p in your code.
}
I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.
I have an array that looks like
[products] => Array
(
[0] => stdClass Object
(
[order_product_id] => 91385
[order_id] => 5065
[nid] => 2140
[title] => Gi Treasure
[manufacturer] =>
[model] => giftcard
[qty] => 5
[cost] => 0.00000
[price] => 25.00000
[weight] => 0
[data] => Array
(
[gift_description] => HJello!
[gift_email] => dubccom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => Thesure
[gift_card] => 2130
[gift_price] => 25
[gift_qty] => 5
[gift_name] => Steveek
[module] => uc_product
[cert_code] => 8-x8mfqXyUYXze
)
[order_uid] => 1
)
[1] => stdClass Object
(
[order_product_id] => 91386
[order_id] => 5065
[nid] => 2140
[title] => Gift asure 2
[manufacturer] =>
[model] => giftcard
[qty] => 1
[cost] => 0.00000
[price] => 35.00000
[weight] => 0
[data] => Array
(
[gift_description] => Hello There!
[gift_email] => dubcaom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => The Holida
[gift_card] => 2134
[gift_price] => 35
[gift_qty] => 1
[gift_name] => Steven
[module] => uc_product
[cert_code] => 9-8xsxgDW9yrMq
)
[order_uid] => 1
)
)
And I want to get the data array from array of products where the order_product_id (so if it was 91385 I would get
[data] => Array
(
[gift_description] => Hello
[gift_email] => dubccom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => Thesure
[gift_card] => 2130
[gift_price] => 25
[gift_qty] => 5
[gift_name] => Steveek
[module] => uc_product
[cert_code] => 8-x8mfqXyUYXze
)
Any help how I could do so?
function search_products($id,$products)
{
$id = intval($id);
foreach($products as $product)
{
if($product->order_product_id == $id)
{
return($product->data);
}
}
return null;
}
An educated guess at what you're looking for. Call it like search_products(91385, $products). If it returns null, it hasn't found the product ID. I also added a call to intval so if you're relying on user input for this, it'll be an int regardless. If you already sanitize it to an int, this doesn't hurt.
EDIT: Misread original post. Updated from array syntax to object property syntax.
function data_by_order ($arr, $orderId) {
foreach ($arr as $item) { // Loop the array
if ($item->order_product_id == $orderId) { // Test this item for the right order id
return $item->data; // Return the data array
}
}
return FALSE; // Return false if we didn't find it
}
// Example usage:
$data = data_by_order($array,91385);
print_r($data);
$prod_data = false;
foreach ($products as $product)
{
if ($product->order_product_id == 91385)
{
$prod_data = $product->data;
break;
}
}
if ($prod_data) {
// knock yourself out
}
Quite similar to plain English, huh?