PHP: check if object/array is a reference - php

Sorry to ask, its late and I can't figure a way to do it... anyone can help?
$users = array(
array(
"name" => "John",
"age" => "20"
),
array(
"name" => "Betty",
"age" => "22"
)
);
$room = array(
"furniture" => array("table","bed","chair"),
"objects" => array("tv","radio","book","lamp"),
"users" => &$users
);
var_dump $room shows:
...
'users' => &
...
Which means "users" is a reference.
I would like to do something like this:
foreach($room as $key => $val) {
if(is_reference($val)) unset($room[$key]);
}
The main goal is to copy the array WITHOUT any references.
Is that possible?
Thank you.

You can test for references in a multi-dimensional array by making a copy of the array, and then altering and testing each entry in turn:
$roomCopy = $room;
foreach ($room as $key => $val) {
$roomCopy[$key]['_test'] = true;
if (isset($room[$key]['_test'])) {
// It's a reference
unset($room[$key]);
}
}
unset($roomCopy);
With your example data, $room['furniture'] and $roomCopy['furniture'] will be separate arrays (as $roomCopy is a copy of $room), so adding a new key to one won't affect the other. But, $room['users'] and $roomCopy['users'] will be references to the same $users array (as it's the reference that's copied, not the array), so when we add a key to $roomCopy['users'] it is visible in $room['users'].

The best I can manage is a test of two variables to determine if one is a reference to the other:
$x = "something";
$y = &$x;
$z = "something else";
function testReference(&$xVal,&$yVal) {
$temp = $xVal;
$xVal = "I am a reference";
if ($yVal == "I am a reference") { echo "is reference<br />"; } else { echo "is not reference<br />"; }
$xVal = $temp;
}
testReference($x,$y);
testReference($y,$x);
testReference($x,$z);
testReference($z,$x);
testReference($y,$z);
testReference($z,$y);
but I doubt if it's much help
Really dirty method (not well tested either):
$x = "something";
$y = &$x;
$z = "something else";
function isReference(&$xVal) {
ob_start();
debug_zval_dump(&$xVal);
$dump = ob_get_clean();
preg_match('/refcount\((\d*)\)/',$dump,$matches);
if ($matches[1] > 4) { return true; } else { return false; }
}
var_dump(isReference($x));
var_dump(isReference($y));
var_dump(isReference($z));
To use this last method in your code, you'd need to do something like:
foreach($room as $key => $val) {
if(isReference($room[$key])) unset($room[$key]);
}
because $val is never a reference as it's a copy of the original array element; and using &$val makes it always a reference

something recursive maybe.
function removeReferences($inbound)
{
foreach($inbound as $key => $context)
{
if(is_array($context))
{
$inbound[$key] = removeReferences($context)
}elseif(is_object($context) && is_reference($context))
{
unset($inbound[$key]); //Remove the entity from the array.
}
}
return $inbound;
}

function var_reference_count(&$xVal) {
$ao = is_array($xVal)||is_object($xVal);
if($ao) { $temp= $xVal; $xVal=array(); }
ob_start();
debug_zval_dump(&$xVal);
$dump = ob_get_clean();
if($ao) $xVal=$temp;
preg_match('/refcount\((\d*)\)/',$dump,$matches);
return $matches[1] - 3;
}
//-------------------------------------------------------------------------------------------
This works with HUDGE objects and arrays.

if you want to get rid of recursive elements:
<?php
$arr=(object)(NULL); $arr->a=3; $arr->b=&$arr;
//$arr=array('a'=>3, 'b'=>&$arr);
print_r($arr);
$arr_clean=eval('return '.strtr(var_export($arr, true), array('stdClass::__set_state'=>'(object)')).';');
print_r($arr_clean);
?>
output:
stdClass Object ( [a] => 3 [b] => stdClass Object *RECURSION* )
stdClass Object ( [a] => 3 [b] => )

Related

Avoid Nested Loop in PHP

I am writing a method which takes an array of $topicNames and an array of $app and concatenates each $app to $topicNames like the following
public function getNotificationTopicByAppNames(array $topicNames, array $apps)
{
$topics = [];
foreach ($topicNames as $topicName) {
foreach ($apps as $app) {
$topic = $app . '_' . $topicName;
$topics[] = $topic;
}
}
return $topics;
}
}
The input and result are like the following...
$topicNames = [
'one_noti',
'two_noti',
'three_noti'
];
$apps = [
'one_app',
'two_app'
];
// The return result of the method will be like the following
[
'one_app_one_noti',
'two_app_one_noti',
'one_app_two_noti',
'two_app_two_noti',
'one_app_three_noti',
'two_app_three_noti'
]
My question is instead of doing nested loops, is there any other way I can do? Why do I want to avoid nested loops? Because currently, I have $topic. Later, I might want to add languages, locations etc...
I know I can use map, reduce, array_walks, each those are basically going through one by one. Instead of that which another alternative way I can use? I am okay changing different data types instead of the array as well.
If you dont care about the order you can use this
function getNotificationTopicByAppNames(array $topicNames, array $apps)
{
$topics = [];
foreach($apps as $app){
$topics = array_merge($topics, preg_filter('/^/', $app.'_', $topicNames));
}
return $topics;
}
print_r(getNotificationTopicByAppNames($topicNames,$apps));
Output
Array
(
[0] => one_app_one_noti
[1] => one_app_two_noti
[2] => one_app_three_noti
[3] => two_app_one_noti
[4] => two_app_two_noti
[5] => two_app_three_noti
)
Sandbox
You can also switch loops and use the $ instead to postfix instead of prefix. Which turns out to be in the same order you had. I thought of prefixing as a way to remove the loop. Then i thought why not flip it.
function getNotificationTopicByAppNames(array $topicNames, array $apps)
{
$topics = [];
foreach($topicNames as $topic){
$topics = array_merge($topics, preg_filter('/$/', '_'.$topic, $apps));
}
return $topics;
}
print_r(getNotificationTopicByAppNames($topicNames,$apps));
Output
Array
(
[0] => one_app_one_noti
[1] => two_app_one_noti
[2] => one_app_two_noti
[3] => two_app_two_noti
[4] => one_app_three_noti
[5] => two_app_three_noti
)
Sandbox
The trick here is using preg_filter.
http://php.net/manual/en/function.preg-filter.php
preg_filter — Perform a regular expression search and replace
So we search with ^ start or $ end which doesn't capture anything to replace and then we just add on what we want. I've used this before when I wanted to prefix a whole array with something, etc.
I couldn't test it in a class, so I made it a regular function, so adjust as needed.
Cheers!
You can use :
<?php
public function mergeStacks(...$stacks)
{
$allStacks = call_user_func_array('array_merge', $stacks);
return $this->concatString($allStacks);
}
private function concatString(&$stack, $index = 0, &$result = [])
{
if(count($stack) == 0){
return '';
}
if($index == count($stack)){
return $result;
}
array_walk($stack, function($value, $key) use($index, &$result, $stack){
if($key > $index){
array_push($result, $stack[$index] . '_' . $value);
}
});
$index = $index + 1;
return $this->concatString($stack, $index, $result);
}
And then when you want to get the array, no matter if you have languages or topics etc, you can just do :
$this->mergeStacks($languages, $topics, $locations, .....);
Where $languages, $topics, $locations are simple arrays.
Instead of accepting only topics name parameter try something like this:
function getNotificationTopicByAppNames(array $apps, array ...$names)
{
$topics = [];
foreach ($names as $nameArray) {
foreach ($nameArray as $topicName) {
foreach ($apps as $app) {
$topic = $app . '_' . $topicName;
$topics[] = $topic;
}
}
}
return $topics;
}
$topicNames = [
'one_noti',
'two_noti',
'three_noti'
];
$languagesNames = [
'test_en',
'test_other',
'test_other2'
];
$apps = [
'one_app',
'two_app'
];
print_r(getNotificationTopicByAppNames($apps,$topicNames,$languagesNames));
you can pass any number of arrays to array.

Convert PHP array from XML that contains duplicate elements

Up until now, I've been using the snippet below to convert an XML tree to an array:
$a = json_decode(json_encode((array) simplexml_load_string($xml)),1);
..however, I'm now working with an XML that has duplicate key values, so the array is breaking when it loops through the XML. For example:
<users>
<user>x</user>
<user>y</user>
<user>z</user>
</users>
Is there a better method to do this that allows for duplicate Keys, or perhaps a way to add an incremented value to each key when it spits out the array, like this:
$array = array(
users => array(
user_1 => x,
user_2 => y,
user_3 => z
)
)
I'm stumped, so any help would be very appreciated.
Here is a complete universal recursive solution.
This class will parse any XML under any structure, with or without tags, from the simplest to the most complex ones.
It retains all proper values and convert them (bool, txt or int), generates adequate array keys for all elements groups including tags, keep duplicates elements etc etc...
Please forgive the statics, it s part of a large XML tools set I used, before rewriting them all for HHVM or pthreads, I havent got time to properly construct this one, but it will work like a charm for straightforward PHP.
For tags, the declared value is '#attr' in this case but can be whatever your needs are.
$xml = "<body>
<users id='group 1'>
<user>x</user>
<user>y</user>
<user>z</user>
</users>
<users id='group 2'>
<user>x</user>
<user>y</user>
<user>z</user>
</users>
</body>";
$result = xml_utils::xml_to_array($xml);
result:
Array ( [users] => Array ( [0] => Array ( [user] => Array ( [0] => x [1] => y [2] => z ) [#attr] => Array ( [id] => group 1 ) ) [1] => Array ( [user] => Array ( [0] => x [1] => y [2] => z ) [#attr] => Array ( [id] => group 2 ) ) ) )
Class:
class xml_utils {
/*object to array mapper */
public static function objectToArray($object) {
if (!is_object($object) && !is_array($object)) {
return $object;
}
if (is_object($object)) {
$object = get_object_vars($object);
}
return array_map('objectToArray', $object);
}
/* xml DOM loader*/
public static function xml_to_array($xmlstr) {
$doc = new DOMDocument();
$doc->loadXML($xmlstr);
return xml_utils::dom_to_array($doc->documentElement);
}
/* recursive XMl to array parser */
public static function dom_to_array($node) {
$output = array();
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) {
$child = $node->childNodes->item($i);
$v = xml_utils::dom_to_array($child);
if (isset($child->tagName)) {
$t = xml_utils::ConvertTypes($child->tagName);
if (!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
} elseif ($v) {
$output = (string) $v;
}
}
if (is_array($output)) {
if ($node->attributes->length) {
$a = array();
foreach ($node->attributes as $attrName => $attrNode) {
$a[$attrName] = xml_utils::ConvertTypes($attrNode->value);
}
$output['#attr'] = $a;
}
foreach ($output as $t => $v) {
if (is_array($v) && count($v) == 1 && $t != '#attr') {
$output[$t] = $v[0];
}
}
}
break;
}
return $output;
}
/* elements converter */
public static function ConvertTypes($org) {
if (is_numeric($org)) {
$val = floatval($org);
} else {
if ($org === 'true') {
$val = true;
} else if ($org === 'false') {
$val = false;
} else {
if ($org === '') {
$val = null;
} else {
$val = $org;
}
}
}
return $val;
}
}
You can loop through each key in your result and if the value is an array (as it is for user that has 3 elements in your example) then you can add each individual value in that array to the parent array and unset the value:
foreach($a as $user_key => $user_values) {
if(!is_array($user_values))
continue; //not an array nothing to do
unset($a[$user_key]); //it's an array so remove it from parent array
$i = 1; //counter for new key
//add each value to the parent array with numbered keys
foreach($user_values as $user_value) {
$new_key = $user_key . '_' . $i++; //create new key i.e 'user_1'
$a[$new_key] = $user_value; //add it to the parent array
}
}
var_dump($a);
First of all this line of code contains a superfluous cast to array:
$a = json_decode(json_encode((array) simplexml_load_string($xml)),1);
^^^^^^^
When you JSON-encode a SimpleXMLElement (which is returned by simplexml_load_string when the parameter could be parsed as XML) this already behaves as-if there would have been an array cast. So it's better to remove it:
$sxml = simplexml_load_string($xml);
$array = json_decode(json_encode($sxml), 1);
Even the result is still the same, this now allows you to create a subtype of SimpleXMLElement implementing the JsonSerialize interface changing the array creation to your needs.
The overall method (as well as the default behaviour) is outlined in a blog-series of mine, on Stackoverflow I have left some more examples already as well:
PHP convert XML to JSON group when there is one child (Jun 2013)
Resolve namespaces with SimpleXML regardless of structure or namespace (Oct 2014)
XML to JSON conversion in PHP SimpleXML (Dec 2014)
Your case I think is similar to what has been asked in the first of those three links.

PHP Add New Index to Multidimentional Array Without Notice

Take this example:
$data = array();
$data['a']['one'] = 'test';
This will throw a notice because $data['a'] doesn't exist. So instead, I always do this:
$data = array();
$data['a'] = array();
$data['a']['one'] = 'test';
Or if I'm in a loop, something like this:
$data = array();
foreach ($items as $item) {
if (!isset($data['a'])) {
$data['a'] = array();
}
$data['a']['one'] = $item->getId();
}
This gets really reptitive in the code and messy. I know that I could write some kind of array_push alternative function to handle this, but I'm wondering if there is a way to do this with existing PHP methods.
Initialising the entire array (all keys, sub arrays etc) somewhere first is not practical.
This means remembering and maintaining it - when you have new data not previously accounted for, you have to also add it to the array initialisation.
(Urgh)
I would least delcare the var as an array ($data = array();) then you don't need is_array() - which is an annoying single line of code before you even do anything useful (two lines including the closing brace..).
However, your checking is not needed.
Your code checks if the array's sub array has been set, and if not you set it as an array and then set the data onto it.
This is not necessary, as you can set data in an array even if some of the sub keys/arrays had not previously been set.
For example this code (this is the entire file and all code ran) won't throw an error, warning, or notice:
$data['a']['one']['blah']['foo'] = 'test';
print_r($data);
echo $data['a']['one']['blah']['foo'];
The above outputs:
Array ([a] => Array ( [one] => Array ( [blah] => Array ( [foo] => test ) ) ) )
test
The above code will not return any warning/notice/errors.
Also notice I didn't even have $data = array().
(although you want to, as you likely use foreach and that initialisation negates the need for using is_array).
That was with error_reporting(-1);
TL;DR; - The Answer
So to answer your question, in your code you could do this (and receive no errors/notices/warnings):
$data = array();
// more data setting the array up
foreach ($items as $item) {
$data['a']['one'] = $item->getId();
}
You might wish to look into ArrayObject class, the following runs without errors or warnings
<?php
error_reporting(E_ALL| E_NOTICE);
ini_set('display_errors', 1);
$ar = new ArrayObject();
$ar['foo']['bar'] = 1;
assert($ar['foo']['bar'] === 1);
Checkout the ideone
Create the array during assignment:
$data=[];
$data['a'] = ['one' => 'test'];
Or create the whole structure in one go
$data = ['a'=>['one'=>'test']];
I dont believe there are any built in methods that suit your needs: PHP array functions
Maybe creating your own function would be the neatest way to achieve this. Or, depending on your use case you could create your array of data to add to key a separately like below:
$data = array();
$array_data = array();
foreach ($items as $key => $item) {
$array_data[$key] = $item->getId(); // presuming your 'one' is a dynamic key
}
$data['a'] = $array_data;
Whether or not this a better than your approach is a matter of opinion I suppose.
You can bypass notices by adding #. Also you can disable notices which I don't recommend at all.
I think there are better ways to write such codes:
$a['one'] = 'test';
$a['two'] = 'test';
$data['a'] = $a;
or:
$data['a'] = ['one'=>'test', 'two'=>'test']
or:
$data = ['a'=>['one'=>'test', 'two'=>'test']];
The methods that multiple people have suggested to simply create the array as a multidimensional array from the beginning is typically not an option when dealing with dynamic data. Example:
$orderItems = array();
foreach ($items as $item) {
$oId = $order->getId();
if (!isset($orderItems[$oId])) {
$orderItems[$oId] = array();
}
$pId = $item->getPackageNumber();
if (!isset($orderItems[$oId][$pId])) {
$orderItems[$oId][$pId] = array('packages'=>array());
}
$orderItems[$oId][$pId][] = $item;
}
It sounds like I need to create a function to do this for me. I created this recursive function which seems to do the job:
function array_md_push(&$array, $new) {
foreach ($new as $k => $v) {
if (!isset($array[$k])) {
$array[$k] = array();
}
if (!is_array($v)) {
array_push($array[$k], $v);
} else {
array_md_push($array[$k], $v);
}
}
}
$test = array();
$this->array_md_push($test, array('a' => array('one' => 'test')));
$this->array_md_push($test, array('a' => array('one' => 'test two')));
$this->array_md_push($test, array('a' => array('two' => 'test three')));
$this->array_md_push($test, array('b' => array('one' => 'test four')));
Which gives me this:
array(2) {
["a"] => array(2) {
["one"] => array(2) {
[0] => string(4) "test"
[1] => string(8) "test two"
}
["two"] => array(1) {
[0] => string(10) "test three"
}
}
["b"] => array(1) {
["one"] => array(1) {
[0] => string(9) "test four"
}
}
}
This works. You do not need to set as an empty array
$data['a']['one'] = 'test';

Get keys from multidimensional array according to other keys

I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}

How to create a nested array out of an array in PHP

Say, we have an array: array(1,2,3,4,...)
And I want to convert it to:
array(
1=>array(
2=>array(
3=>array(
4=>array()
)
)
)
)
Can anybody help?
Thanks
EDIT It would be good to have the solution with iterations.
$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
$temp = array($array[$i] => $temp);
}
You can simply make a recursive function :
<?php
function nestArray($myArray)
{
if (empty($myArray))
{
return array();
}
$firstValue = array_shift($myArray);
return array($firstValue => nestArray($myArray));
}
?>
Well, try something like this:
$in = array(1,2,3,4); // Array with incoming params
$res = array(); // Array where we will write result
$t = &$res; // Link to first level
foreach ($in as $k) { // Walk through source array
if (empty($t[$k])) { // Check if current level has required key
$t[$k] = array(); // If does not, create empty array there
$t = &$t[$k]; // And link to it now. So each time it is link to deepest level.
}
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();
Output:
array(1) {
[1]=> array(1) {
[2]=> array(1) {
[3]=> array(1) {
[4]=> array(0) {
}
}
}
}
}
I think the syntax for the multidimensional array you want to create would look like the following.
$array = array(
'array1' => array('value' => 'another_value'),
'array2' => array('something', 'something else'),
'array3' => array('value', 'value')
);
Is this what you're looking for?
You can also use this array library to do that in just one line:
$array = Arr::setNestedElement([], '1.2.3.4', 'value');

Categories