PHP Display The Array Index of Object - php

Following code
echo '<pre>';
foreach($this->allcategories as $k){
var_dump($k);
}
is displaying
object(Application_Model_Categories {
["_data":"Application_Model_Base":private]=> array(7) {
["CategoriesName"]=> string(8) "Clothing"
}
}
but I need just the CategoriesName i.e Clothing, nothing else.

Write this in your class
public function getX(){
return $this->_data;
}
And call this from where you want the data.
$data = $this->getX();
echo $data["CategoriesName"];

This should only print "Clothing":
foreach($this->allcategories as $k){
$cat = $k['CategoriesName'];
var_dump($cat);
}

Related

Combine Sub-array values into a single array withing an array

I may not word this issue properly, so here's what am trying to achieve.
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 }
}
[1]=> {
["Abilities"]=> { ["Verbal"]=> 1 }
}
[2]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
to
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 ["Verbal"]=> 1 }
}
[1]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
I get this array from an external source so I need optimized this way to use it.
The array you're getting from an external source is like a set of separate branches you need to merge into a single tree. You can use a recursive function to create the "optimized" structure you're going for. A recursive approach should work regardless of the depth of each branch.
function merge_branches(array $branches): array
{
$merge = function ($node, &$tree) use (&$merge) {
if (is_array($value = reset($node))) {
$merge($value, $tree[key($node)]); // merge branch node recursively
} else {
$tree[key($node)] = $value; // set leaf node to value
}
};
$tree = [];
foreach ($branches as $branch) {
$merge($branch, $tree);
}
return $tree;
}
$optimized = merge_branches($external);

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

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));

jquery autocomplete plugin - fetch works - fetchAll doesn't

If I have something like this from the server side, from a fetch:
array(1) { [0]=> array(1) { ["nome"]=> string(7) "aaaa.br" } } [{"nome":"aaaa.br"}]
The json of the above is:
[{"nome":"aaaa.br"}]
This Works:
parse: function(data) {
return $.map(eval('('+data+')'), function(result) {
return {
data: result,
value: result.nome,
result: result.nome
}
});
}
The result is parsed successfully.
If, instead of fetch, I change to fetchAll, the dump gets like this (here only the first index as example):
array(65) { [0]=> array(1) { ["nome"]=> object(stdClass)#7 (1) { ["nomeDominio"]=> string(7) "aaaa.br" } }
The json conversion of the above:
string(2632) "[{"nome":{"nomeDominio":"aaaa.br"}}
Here, the result is not successfully parsed.
So I believe something needs to be changed on the js side.
But I'm absolutely clueless.
UPDATE:
The nomeDominio is from the fetchObj PDO method, and corresponds to the column name on the database. It's a natural behaviour for fetch with PDO when FETCH::OBJ option is used.
The php part of this js is:
$keyword = addslashes($_GET["q"]);
$comandos = new ComandoController();
$arr = $comandos->recebeNomeDominios($keyword);
if(is_array($arr))
{
echo json_encode($arr);
}
public function recebeNomeDominios($keyword)
{
$DominioDao = new DominioDao();
$objecto = $DominioDao->recebeNomeDominios($keyword);
return $this->jsonArray($objecto);
}
private function jsonArray($objecto)
{
$json = array();
if(isset($objecto) && !empty($objecto))
{
foreach($objecto as $obj)
{
$json[] = array('nome' => $obj);
}
}
return $json;
}
Finally:
public function recebeNomeDominios($keyword)
{
try
{
$stmt = $this->_dbh->prepare("SELECT d.nomeDominio FROM dominio d WHERE d.nomeDominio LIKE '%".$keyword."%'");
$stmt->execute();
$resultado = $stmt->fetch(PDO::FETCH_OBJ);
return $resultado;
}
catch (PDOException $ex)
{
echo "Erro: " . $ex->getMessage();
}
}
Any advice?
MEM
$comandos = new ComandoController();
$arr = $comandos->recebeNomeDominios($keyword);
echo json_encode($arr);
class ComandoController {
public function recebeNomeDominios($keyword)
{
$stmt = $this->_dbh->prepare('
SELECT
d.nomeDominio as nome
FROM
dominio
WHERE nomeDominio LIKE :keyword
');
$stmt->bindParam(':keyword', $keyparam);
$keyparam = '%'.str_replace('%', '\\%', $keyword) . '%';
$stmt->execute();
return $stmt->fetchALL(PDO::FETCH_ASSOC);
}
...
If you return one array (fetch) then you need to collect data from it like this
var name = data.name;
var age = data.age;
var gender = data.gender;
// Do something with values here
If you are using fetchAll, this will presumably return an array of arrays (a multidimensional array) which you will need to iterate over. From looking at $.map it looks like your using jQuery. Iterate over the multidimensional array like this
jQuery.each(data, function() {
name = this.name;
age = this.age;
gender = this.gender;
// Do something with values here
});

Categories