Showing data in the form of json and print_r - php

I am trying to form my array in order by date I have find my answer from this question and it is show the desire result through this answer but when I use print_r or json_encode it just show me true.
I don't know why?
The answer method:
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($worth_array, "sortFunction");
echo "<pre>";
var_dump($worth_array);
echo "</pre>";
Result:
array(10) {
[0]=>
array(2) {
["date"]=>
string(10) "2014-06-03"
["worth"]=>
int(1131)
}
[1]=>
array(2) {
["date"]=>
string(10) "2014-06-04"
["worth"]=>
int(4469)
}
}
print_r method:
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
$worth_array_final = usort($worth_array, "sortFunction");
echo "<pre>";
print_r($worth_array_final);
echo "</pre>";
Result: 1

usort returns a boolean (see usort in php manual), and sorts the array passed as a reference. I.e. in your case $worth_array contains the sorted data and $worth_array_final only succes or not.

Related

PHP check if string is in array

I have an array that looks like this:
{"permissions":["1","2"]}
I'm trying to check if a given string is in the permissions array with the following function
function hasPermission($permission) {
return in_array($permission, array_column($this->permissions, 'permissions'));
}
When calling the function giving it the string "1" it return false even though 1 is in the permissions array
Any help would be appreciated
Thanks
EDIT
Here is a var Dump of the converted array
array(1) {
["permissions"]=>
array(2) {[0]=> string(1) "1"
[1]=> string(1) "2"
}
}
Try like this...
<?php
$json = '{"permissions":["1","2"]}';
$arr = json_decode($json,true);
print_r($arr);
echo in_array(1,$arr['permissions']); // returns 1 if exists
?>
So your function must be like this....
function hasPermission($permission) {
return in_array($permission, $this->permissions['permissions']);
}
array_column doesn't support 1D arrays, it returns an empty array if so.
Your $permissions array is 1D, so just use $this->permissions['permission'] to access it.
return in_array($permission, $this->permissions['permissions']);
Example:
$array = ['permissions' => ['1', '2']];
echo (int)in_array('1', array_column($array, 'permissions')); // 0
echo (int)in_array('1', $array['permissions']); // 1
Try this this will work.
$permission = json_decode('{"permissions":["1","2"]}',true);
echo "<pre>";print_r($permission);
if(is_array($permission)){
echo "this is an array";
}else{
echo "Not an array";
}
Thanks

PHP difference in array parameters

In PHP 7, I want only arrays to be in the parameters, but what is the difference between:
function exampleA(array $a, array $b)
{
}
and
function exampleB($a = array(), $b = array())
{
}
Not sure which I should be using.
The comments are good but I guess we need an answer.
exampleA() using array $a forces the arguments to be of type array and if not it throws a catchable error:
exampleA();
exampleA(1, 'A');
Both yield:
Catchable fatal error: Argument 1 passed to exampleA() must be of the type array, none given, called in file on line X and defined in file on line X
Whereas in exampleB() using $a = array():
function exampleB($a = array(), $b = array())
{
var_dump(get_defined_vars());
}
Sets default values to empty arrays when no values are supplied:
exampleB();
Yields:
array(2) { ["a"]=> array(0) { } ["b"]=> array(0) { } }
However, when values are supplied those values are used regardless of type:
exampleB(1, 'A');
Yields:
array(2) { ["a"]=> int(1) ["b"]=> string(1) "A" }

How to add (any type )value to an array(by specified index) in php language

As title, I did it like below:
$array=array(0,1,2,3);
$result=array();
function makeArray($array,$result,$value){
$str='$result';
for ($i=0;$i<count($array);$i++){
$str.='['.$i.']';
}
$str.='="'.$value.'";';
eval($str);
return $result;
}
It can realize result when param $result is an empty array,but It report an error when $result is an array.
Error like :
Cannot use a scalar value as an array.
Anyways can realize it?
Thanks first!
Use pass by reference, not eval:
function makeArray($indexes, &$result, $value) {
$here =& $result;
foreach ($indexes as $i) {
if (!(isset($here[$i]) && is_array($here[$i]))) {
$here[$i] = array();
}
$here =& $here[$i];
}
$here = $value;
}
$array=array(0,1,2,3);
$result=array();
makeArray($array, $result, 3);
var_dump($result);
Output:
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[2]=>
array(1) {
[3]=>
int(3)
}
}
}
}
Putting & before a function parameter means it will be passed by reference, so modifications to the variable inside the function will affect the original variable that was passed. And using =& in an assignment assigns a reference, so the target variable is an alias for the source.

Convert multidimensional objects to array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 6 months ago.
I'm using amazon product advertising api. Values are returned as a multidimensional objects.
It looks like this:
object(AmazonProduct_Result)#222 (5) {
["_code":protected]=>
int(200)
["_data":protected]=>
string(16538)
array(2) {
["IsValid"]=>
string(4) "True"
["Items"]=>
array(1) {
[0]=>
object(AmazonProduct_Item)#19 (1) {
["_values":protected]=>
array(11) {
["ASIN"]=>
string(10) "B005HNF01O"
["ParentASIN"]=>
string(10) "B008RKEIZ8"
["DetailPageURL"]=>
string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
["ItemLinks"]=>
array(7) {
[0]=>
object(AmazonProduct_ItemLink)#18 (1) {
["_values":protected]=>
array(2) {
["Description"]=>
string(17) "Technical Details"
["URL"]=>
string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
}
}
[1]=>
object(AmazonProduct_ItemLink)#17 (1) {
["_values":protected]=>
array(2) {
I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.
I know this is old but you could try the following piece of code:
$array = json_decode(json_encode($object), true);
where $object is the response of the API.
You can use recursive function like below:
function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}
return $arr;
}
function convertObjectToArray($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
return $data;
}
Credit to Kevin Op den Kamp.
I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.
function is_json($string) {
// php 5.3 or newer needed;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function objectToArray($objectOrArray) {
// if is_json -> decode :
if (is_string($objectOrArray) && is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);
// if object -> convert to array :
if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;
// if not array -> just return it (probably string or number) :
if (!is_array($objectOrArray)) return $objectOrArray;
// if empty array -> return [] :
if (count($objectOrArray) == 0) return [];
// repeat tasks for each item :
$output = [];
foreach ($objectOrArray as $key => $o_a) {
$output[$key] = objectToArray($o_a);
}
return $output;
}
This is an old question, but I recently ran into this and came up with my own solution.
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:
$array = (array)$object;
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
And the mini-example:
array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});
In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.
I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.
Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:
protected function objToArray($obj)
{
// Not an object or array
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
// Parse array
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
// Return parsed array
return $arr;
}
The original value is a JSON string. The method call looks like this:
$array = $this->objToArray(json_decode($json, true));

Get list of {} templates from String [PHP]

I want to get the template words in a string. Template in the sense of words in {} inside a string. I am adding here a code to explain what I want exactly.
$string = "Hi {username}, Here is your {password}";
function get_template_variables($string)
{
....
....
return array();
}
$result = get_template_variables($string);
print_r($result);
array[
0 => username,
1 => password
]
I hope you understand what I need. I need the definition program to be used inside the get_template_variables($string) method
function get_template_variables($string) {
preg_match_all('/{([^}]+)}/', $string, $matches);
return $matches[1];
}
You can do:
function get_template_variables($string) {
if(preg_match_all('/\{(.*?)\}/',$string,$m)) {
return $m[1]
}
return array();
}
preg_match_all('/{.*}/U' , $string , $a );
where $result will be
array(1) {
[0]=>
array(2) {
[0]=>
string(10) "{username}"
[1]=>
string(10) "{password}"
}
}

Categories