php print array contents - php

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.
}

Related

Edit a specific key value of an object inside an array of objects (JSON)

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

PHP - loop through messages in array

I have weird problem with my PHP code. I decoded an elasticsearch json, and I got this array:
Array ( [took] => 1 [timed_out] => [_shards] => Array ( [total] => 6 [successful] => 6 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => 7336 [max_score] => 0.8790647 [hits] => Array ( [0] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 5T8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [#version] => 1 [log-level] => ERROR [port] => 50906 [host] => 6b14cd1f183d.mynetwork [#timestamp] => 2019-02-25T14:20:01.367Z [Timestamp] => 2019-02-25T13:57:40+0000 [message] => Array ( [0] => 2019-02-25T13:57:40+0000 ERROR something happened in this execution. [1] => something happened in this execution. ) ) ) [1] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 7z8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [#version] => 1 [log-level] => INFO [port] => 50906 [host] => 6b14cd1f183d.mynetwork [#timestamp] => 2019-02-25T14:20:01.369Z [Timestamp] => 2019-02-25T14:00:13+0000 [message] => Array ( [0] => 2019-02-25T14:00:13+0000 INFO takes the value and converts it to string. [1] => takes the value and converts it to string. ) ) ) ) ) )
What I want is only to print the "messages".
If I run this code:
$echo json_decoded['hits']['hits']['0']['_source']['message']['0']
It echo "2019-02-25T13:57:40+0000 ERROR something happened in this execution."
And if I run this code:
$echo json_decoded['hits']['hits']['1']['_source']['message']['0']
It echo "2019-02-25T14:00:13+0000 INFO takes the value and converts it to string."
ALL GOOD SO FAR, but now I want to run it as loop, to print the messages. I made the following loop:
foreach($json_decoded['hits']['hits'] as $host) {
echo $host[$index]['_source']['message']['0'];
$index++;
}
I don't get any output. What is the problem?
When you foreach over ['hits']['hits'] this will iterate over the next level of the array (so the ['0'] and ['1'] elements). So you don't need to add in the [$index] part of your echo or the $index value...
foreach($json_decoded['hits']['hits'] as $host) {
echo $host['_source']['message']['0'];
}

Recursive PHP function is returning unexpected array

I have a hierarchical data that I put in a array that I call $dt. Than I have a array that store the relationship between these data that I call $in. I have create a function that has as parameter, the initial index, level, array $dt an the array $in. I was debugging the function but I am not find why the subclass is lost during the process. The complete code is:
$dt = array(
41=>array( "pk"=>41,"parentPk"=>30,"name"=>"car1"),
15=>array("pk"=>15,"parentPk"=>11,"name"=>"food" ),
70=>array("pk"=>70,"parentPk"=>30,"name"=>"car3" ),
18=>array("pk"=>18,"parentPk"=>15,"name"=>"food1" ),
49=>array("pk"=>49,"parentPk"=>30,"name"=>"car2" ),
20=>array( "pk"=>20,"parentPk"=>15,"name"=>"food2"),
30=>array("pk"=>30,"parentPk"=>11,"name"=>"car" )
);
echo "<pre>";
print_r($dt);
echo "</pre>";
$in=array(11=>array(15,30),15=>array(18,20),30=>array(41,49,70));
echo "<pre>";
print_r($in);
echo "</pre>";
function fn_tree($parent_id, $level,$dt,$in) {
if(is_null($parent_id)){
$parent_id ="NULL";
}
if (isset($in[$parent_id])) {
foreach ($in[$parent_id] as $id) {
$pk=$in[$parent_id];
$arrEnd[$id]=str_repeat("-", $level*2) .$dt[$id]["name"];
fn_tree($id, $level + 1,$dt,$in,$arrEnd);
}
}
return $arrEnd;
}
$arrEcho = fn_tree(11, 0, $dt, $in);
echo "<br>";
echo "result";
echo "<br>";
echo "<pre>";
print_r($arrEcho);
echo "</pre>";
$desired = array(
15=>"food",
18=>"food1",
20=>"food2",
30=>"car",
41=>"car1",
49=>"car2",
70=>"car3"
);
echo "<br>";
echo "desired";
echo "<br>";
echo "<pre>";
print_r($desired);
echo "</pre>";
So why the function is losting the sub-classes?
Output is:
Array data
(
[41] => Array
(
[pk] => 41
[parentPk] => 30
[name] => car1
)
[15] => Array
(
[pk] => 15
[parentPk] => 11
[name] => food
)
[70] => Array
(
[pk] => 70
[parentPk] => 30
[name] => car3
)
[18] => Array
(
[pk] => 18
[parentPk] => 15
[name] => food1
)
[49] => Array
(
[pk] => 49
[parentPk] => 30
[name] => car2
)
[20] => Array
(
[pk] => 20
[parentPk] => 15
[name] => food2
)
[30] => Array
(
[pk] => 30
[parentPk] => 11
[name] => car
)
)
Array relationship
(
[11] => Array
(
[0] => 15
[1] => 30
)
[15] => Array
(
[0] => 18
[1] => 20
)
[30] => Array
(
[0] => 41
[1] => 49
[2] => 70
)
)
result
Array
(
[15] => food
[30] => car
)
desired
Array
(
[15] => food
[18] => food1
[20] => food2
[30] => car
[41] => car1
[49] => car2
[70] => car3
)
The clue to your problem is/should have been "Undefined variable: arrEnd." If you aren't running in an environment where you can see this warning, you should try to set up such an environment. If you are running in such an environment, you should play close attention to this and all other warnings.
I'm not sure if it is the convention here to just give a clue or a whole answer, but proceeding on to give a fairly complete answer: it seems that you intended to pass arrEnd in by reference, but did not pass it in at all.
Also, I'm a little confused by your desired output. Don't you in fact desire something with double dashes showing hierarchy, as below?
Array
(
[15] => food
[18] => --food1
[20] => --food2
[30] => car
[41] => --car1
[49] => --car2
[70] => --car3
)

Stackoverflow API getting answers in array PHP

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.

Search array? Then get sub values?

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?

Categories