Array of objects not altered after first file write - php

I have an empty array in a remote file but intend to momentarily add and alter objects in it. However, after adding an initial first set of objects, the array does not accept any more values. My error log reports unexpected 'Object' (T_STRING), expecting ')' meaning it regards the keyword "Object" as a string imputed by me so I guess the problem originates from my array structure. Here is the code I used in adding the objects
include 'all_users.php';
$francis_udeh = new Admin("francis_udeh");
$all_users['francis_udeh'] = $francis_udeh;
$victor_nwafor = new Member("victor_nwafor");
$all_users['victor_nwafor'] = $victor_nwafor;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
returns the following in the remote file
<?php
$all_users = Array
(
[francis_udeh] => Admin Object
(
[name] => francis udeh
[pagename] => francis.udeh
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
[can_delete_comment] => 1
)
[victor_nwafor] => Member Object
(
[name] => victor nwafor
[pagename] => victor.nwafor
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
)
);
?>
(which, by the way, is what I want). However, when I try
include 'all_users.php';
$raheem_sadiq = new Member("raheem_sadiq");
$all_users['raheem_sadiq'] = $raheem_sadiq;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
it returns the error I posted earlier resulting in the array not changing. What am I doing wrong?

You include all_users.php at the beginning of code, but after first file_put_contents() it's a not correct php code in this file.

As #Indra already mentioned: the output given by print_r() is human readable, but not valid php code. If you don't have the possibilty to pass the data via a data storage (like mysql), it might be a workaround to put it to the file with serialize(). Alternatively, you could also use json (as your objects seem to be data access objects of some same kind) and then instantiate the objects remotely.
Hope this helps,
Greetings

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

YouTube Feed has an object called #attributes how can I access it?

I am trying to get a YouTube RSS feed to work but I am struggling to get one of the attributes I need out of it. I have never seen part of the array starting with an # sign so I think it may be some sort of a special element but I'm not sure. Code below and what I have already tried after.
Feed:
<?php
$xml->entry =
SimpleXMLElement::__set_state(array(
'id' => 'yt:video:DjwM9SHJznM',
'title' => 'JD19AT - Joomla! in der Uni - Community-Arbeit als Lehrveranstaltung',
'link' =>
SimpleXMLElement::__set_state(array(
'#attributes' =>
array (
'rel' => 'alternate',
'href' => 'https://www.youtube.com/watch?v=DjwM9SHJznM',
),
)),
'author' =>
SimpleXMLElement::__set_state(array(
'name' => 'J and Beyond e.V.',
'uri' => 'https://www.youtube.com/channel/UCy6ThiEDnalZOd_pgtpBk1Q',
)),
'published' => '2019-03-30T16:49:53+00:00',
'updated' => '2019-05-09T16:56:18+00:00',
));
?>
Code:
$feed = $youtubeChannelFeed;
$xml = simplexml_load_file($feed);
$html = "";
This works $xml->entry->title;
but this doesn't $xml->entry->link it just says "SimpleXML Object"
As it says object I then tried using both -> arrow and ['attribute'] notation.
I tried escaping the # with a \# but that just caused an error.
How can I traverse the tree and get the value of to #attributes->href ?
The way I always try to remember this is that you can use an arrow or brackets to access data in an array or object.
Array begins with A, but it chooses the one that's does not begin with A. Object is the one left over. That's how I remember it at least.
In this case, although it was calling it a SimpleXMLObject it was actually showing me that it's an array in the print_r. So I had to use brackets to access like so:
$xml->entry->link[0]['href']
I couldn't work out how to access #attributes but I remember now that you don't need to know the name to access it, you can do it using number format too.
If I'm honest I don't really know how I could access the first part with arrows as that appears to be an array too.

Object inside an array, passing an object to a PHP method

I have a PHP application with a function that was built to expect information from an API call. However, I'm trying to use this function by passing in information that mimics the API data.
I struggle a bit with arrays and this seems to be an object within an array.
I can access the array that the api provides, so when I use the following code ($triggers is the array the api call returns):
print("<pre>".print_r($triggers,true)."</pre>");
I get the following output:
Array
(
[0] => stdClass Object
(
[triggerid] => 18186
[status] => 0
[value] => 0
)
This is the beginning of the function:
function iterate_triggers($triggers){
$trigger_id_values = array();
foreach($triggers as $trigger) {
//Necessary to show human readable status messages.
$check_status = array(0=>"Up", 1=>"Down", 2=>"Degraded", 3=>"Maintenance");
array_push ($trigger_id_values, [$trigger->triggerid, $trigger->value]);
So if I wanted to pass this function a [triggerid] => 18186 and [value] => 1 how would i do that?
Currently I'm trying:
iterate_triggers(array(0 => array("triggerid" => 18186,"status" => 0,"value" => 1,)));
but this gives me a "Trying to get property of non-object" error. Please be kind to me, I've done my best to research and structure this on my own to no avail.
The easiest way is to cast the assoc array just to an object
In your case this would be
iterate_triggers(array(0 => (object)array("triggerid" => 18186,"status" => 0,"value" => 1,)));
You are currently creating and passing an array that contains an array, while your function expects an array of objects.
You should create your object beforehand, then construct your parameter array, and pass it to your function.
$obj = new \stdClass();
$obj->triggerid = 18186;
$obj->status = 0;
$obj->value = 1;
$arr = array($obj);
iterate_triggers($arr);
This comment on php.net, and the rest of that object documentation, may be useful to you.
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose: <?php $genericObject = new stdClass(); ?>
The error message you are seeing with your own code is caused by $trigger->triggerid inside the function, when $trigger is an array instead of an object as the function expects. Object properties are accessed using $someObject->propertyName notation, while array elements are accessed using $someArray['keyName']

DyanmoDB: not getting the answer I'm expecting using batch_get_item

I am trying to do a batch_get_item to request multiple items from a table. I am following the PHP example in the DynamoDB documentation, but I am not getting the results I'm expecting.
Following is the code:
$batch_array = array ();
$batch_array[]= array ('HashKeyElement' =>
array( AmazonDynamoDB::TYPE_STRING => 'V1L3M5O5L1W8R5B6D2Q1S8V0B3R8M7A6R0X0'));
$options = array (
'RequestItems' => array(
'profile_dev' => array (
'Keys' => $batch_array
)
)
);
$result = $this->db->batch_get_item($options);
Instead of getting the data, I am getting a very long response, and I'm including the relevant information from the tail end of it:
[x-aws-body] => {"RequestItems":{"profile_dev":{"Keys":[{"HashKeyElement":{"S":"V1L3M5O5L1W8R5B6D2Q1S8V0B3R8M7A6R0X0"}}]}}} ) [body] => CFSimpleXML Object ( [__type] => com.amazon.coral.validate#ValidationException [message] => One or more parameter values were invalid: The provided key size does not match with that of the schema ) [status] => 400 ) )
The hashKey for this table is a string. It has a rangeKey, but I am using the hashKey so I can get all the rows matching the hashKey. What am I missing?
The DynamoDB documentation (and SDK samples) have colossal bugs in them. The documentation, and actual SDK code, make use only of the hashKeyElement, but in fact if a table has both a hashKey AND a rangeKey, both must be used.
When I used both the hashKey and the rangeKey, the call worked.
Get (or batch get) requires you to completely define the key of all items you are getting. If you want to retrieve all rows with the same hashKey using a single call, it seems like you're looking for Query.
You don't need to use BatchGet, you should be using Query. Here is an example using the PHP SDK to get all items with the HASH key 'YourHashKey' on table 'YourTable'
// Instantiate the class
$dynamodb = new AmazonDynamoDB();
$response = $dynamodb->query(array(
'TableName' => 'YourTable',
'HashKeyValue' => array( AmazonDynamoDB::TYPE_STRING => 'YourHashKey' ),
));
Reference: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/LowLevelPHPQuerying.html

unserialize problem

I'm facing a problem in unserialize the data from the database table. I'm serialized the data and saved into the table. When i'm retrieving the data i'm not able to get it properly. Below is my code .
$miscel = serialize(array($_POST['Prod_Price'],$_POST['Prod_Cond']));
I successfully inserted the data into the database. In the database table it looks like
s:38:"a:2:{i:0;s:4:"4444";i:1;s:6:"Middle";}
How i can retrieve the data properly?
What exactly is the problem? You should be able to simply call unserialize() to retrieve your data in its original form:
// assuming your database column 'foo' contains
// s:38:"a:2:{i:0;s:4:"4444";i:1;s:6:"Middle";}
$miscel = unserialize($row['foo']);
print_r($miscel);
// returns array([0] => 4444, [1] => 'Middle');
If the problem lies within the fact that the data being serialized is not very readable, you should consider storing the array keys as well:
$miscel = serialize(array('price' => $_POST['Prod_Price'], 'cond' => $_POST['Prod_Cond']));
$records = array(
'name'=>'abc',
'mobile'=>'1234566789',
'address'=>'test',
'email'=>'test#test.com');
$records_serialize = serialize($records);
echo "serialize<br/>";
print_r($records_serialize);
echo "<br/><br/>unserialize<br/>";
$records_unserialize = unserialize($records_serialize);
print_r($records_unserialize);
Here code to use serialize and unserialize
output
serialize
a:4:{s:4:"name";s:3:"abc";s:6:"mobile";s:13:"1234566789";s:7:"address";s:4:"test";s:5:"email";s:13:"test#test.com";}
unserialize
Array ( [name] => abc [mobile] => 1234566789[address] => test [email] => test#test.com )
http://nl2.php.net/manual/en/function.unserialize.php
You need to use the unserialize function. This will return every back into an array.

Categories