Illegal Offset Type Error - php

So I've got the following function:
function sitesync_empty_vals(&$entity) {
$vals = false;
$entity = (array) $entity;
foreach ($entity as $field) {
if (is_array($field)) {
foreach ($field as $lang) {
foreach ($lang as $item) {
if (isset($item['value'])) {
if (empty($item['value'])) {
unset($field[$lang][$item]);
break;
}
else {
$vals = true;
}
}
}
}
if (!$vals && is_array($lang)) {
watchdog("field", print_r($field, true));
unset($field[$lang]);
}
}
}
}
I keep getting the error Illegal offset type.
I'm not quite understanding why I'd be getting this error - it seems to be related to unsetting the $field[$lang][$item] (I don't get the error when I comment it out), but why would that be? Is it because it's trying to iterate over that item after it is unset? In the case that that particular value is empty, I want to unset the whole $item - this is for data normalization between two different servers, one of which doesn't store any data, and one of which stores the data as a 0.

foreach ($lang as $item) {
^^^^---array
unset($field[$lang][$item]);
^^^^^---using Array as array key
You probably want something more like:
foreach($lang as $lang_key => $item) {
unset($field[$lang_key]....);
instead. And as the comments below have noted, $item is ALSO an array, so you'll want a similar treatment for that as well.

Here is a quote from the PHP Docs:
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
http://www.php.net/manual/en/language.types.array.php
You have to use the keys, not the arrays themselves:
function sitesync_empty_vals(&$entity) {
$vals = false;
$entity = (array) $entity;
foreach ($entity as $field) {
if (is_array($field)) {
foreach ($field as $langKey=>$lang) {
foreach ($lang as $itemKey=>$item) {
if (isset($item['value'])) {
if (empty($item['value'])) {
unset($field[$langKey][$itemKey]);
break;
}
else {
$vals = true;
}
}
}
}
if (!$vals && is_array($lang)) {
watchdog("field", print_r($field, true));
unset($field[$langKey]);
}
}
}
}

Related

Function with loop calling same function in PHP

I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.
I have an with some arrays inside it:
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
I am making a function that search for a s
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
break;
}
else {
searchArray($key,$chave,$id);
}
}
}
return $key;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
It was supposed to print ['string6','string7','string99']]
But it it printing the last "key" of the array: ['string8','string9']
The break is not working. After the break, it continue checking the next arrays.
with these modification it returns the expected values:
<?php
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
return $key;
} else {
$res = searchArray($key,$chave,$id);
if($res !== false) {
return $res;
}
}
}
}
return false;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
the failure was to break on success. That makes no sense.
You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.

PHP looping multidimensional array

Not entirely sure how to adequately title this problem, but it entails a need to loop through any array nested within array, of which may also be an element of any other array - and so forth. Initially, I thought it was required for one to tag which arrays haven't yet been looped and which have, to loop through the "base" array completely (albeit it was learned this isn't needed and that PHP somehow does this arbitrarily). The problem seems a little peculiar - the function will find the value nested in the array anywhere if the conditional claus for testing if the value isn't found is omitted, and vice versa. Anyway, the function is as followed:
function loop($arr, $find) {
for($i=0;$i<count($arr);$i++) {
if($arr[$i] == $find) {
print "Found $find";
return true;
} else {
if(is_array($arr[$i])) {
$this->loop($arr[$i], $find);
} else {
print "Couldn't find $find";
return false;
}
}
}
}
Perhaps you should change your code to something like:
var $found = false;
function loop($arr, $find) {
foreach($arr as $k=>$v){
if($find==$v){
$this->found = true;
}elseif(is_array($v)){
$this->loop($v, $find);
}
}
return $this->found;
}
This has been working for me for a while.
function array_search_key( $needle_key, $array ) {
foreach($array AS $key=>$value){
if($key == $needle_key) return $value;
if(is_array($value)){
if( ($result = array_search_key($needle_key,$value)) !== false)
return $result;
}
}
return false;
}
OK, what about a slight modification:
function loop($arr, $find) {
for($i=0;$i<count($arr);$i++) {
if(is_array($arr[$i])) {
$this->loop($arr[$i], $find);
} else {
if($arr[$i] == $find) {
print "Found $find";
return true;
}
}
}
return false;
}
Hmm?
Try this: PHP foreach loop through multidimensional array

PHP arrays - a 'set where key=?' type function?

Is there a built in php function that allows me to set a value of an array based on a matching key? Maybe i've been writing too much SQL lately, but i wish I could perform the following logic without writing out nested foreach array like the following:
foreach($array1 AS $k1 => $a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$array[$k1]['new_key'] = $a2['value'];
}
}
}
Is there a better way to do this? In SQL logic, it would be "SET array1.new_key = x WHERE array1.id = array2.id". Again, i've been writing too much SQL lately :S
When I need to do this, I use a function to first map the values of one array by id:
function convertArrayToMap(&$list, $attribute='id') {
$result = array();
foreach ($list as &$item) {
if (is_array($item) && array_key_exists($attribute, $item)) {
$result[$item[$attribute]] = &$item;
}
}
return $result;
}
$map = convertArrayToMap($array1);
Then iterate through the other array and assign the values:
foreach ($array2 AS $a2) {
$id = $a2['id'];
$map[$id]['new_key'] = $a2['value'];
}
This are less loops overall even for one pass, and it's convenient for further operations in the future.
This one is fine and correct
foreach(&$array1 AS &$a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$a1['new_key'] = $a2['value'];
}
}
}

PHP parsing multidimensional json array of any depth based on key

I have an json array like given below, what I want is to
parse through the array and get a value for corresponding
key .Eg SubAdministrativeAreaName .I could have parsed it
like .
["AddressDetails"]['Country']['AdministrativeArea'] ['SubAdministrativeArea']['SubAdministrativeAreaName']
but the structure of array is not fixed , it may contain some other
keys within which "SubAdmininstrativeArea" may be enclosed .
What I want is a php function that will search for a particular key
name through multidimensional json array of any depth .
Any help would be appreciated .
"AddressDetails": {
"Accuracy": 6,
"Country": {
"AdministrativeArea": {
"AdministrativeAreaName": "Maharashtra",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Parbhani",
"Thoroughfare": {
"ThoroughfareName": "SH217"
}
}
},
"CountryName": "India",
"CountryNameCode": "IN"
}
}
OK, different answer based on comment below:
function array_key_search_deep($needle, $haystack) {
$value = NULL;
if(isset($haystack[$needle])) {
$value = $haystack[$needle];
} else {
foreach($haystack as $node) {
if(is_array($node)) {
$value = array_key_search_deep($needle, $node);
if(!is_null($value)) {
break;
}
}
}
}
return $val;
}
Old Answer
This will allow you to traverse an unknown path in any array tree:
$path = array('AddressDetails', 'Country', 'AdministrativeArea', 'SubAdministrativeArea', 'SubAdministrativeAreaName');
$node = $json_object;
foreach($path as $path_index) {
if(isset($node[$path_index])) {
$node = $node[$path_index];
} else {
$node = NULL;
}
}
echo($node);
Thanks guys , what I made was a a solution like this
I finally found a simple solution myself
For eg) To get "ThoroughfareName" make a call
recursive_array_search($json_array,'ThoroughfareName') ;
function recursive_array_search($arr,$jackpot)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$val=recursive_array_search($value,$jackpot) ;
return $val;
}
else
{
if($key==$jackpot)
return $value;
}
}
}
You could use JSONPath (XPath for JSON)
http://goessner.net/articles/JsonPath/
(with for instance the expression "$..SubAdministrativeAreaName")
EDIT: Haven't tested it, not sure how reliable it is.

Convert array and object with HTML entities

I am trying to write a piece of code, that will recursively convert every string in an array or object to be safe with the quotes for displaying in input boxes.
This is an array I wrote, with parts I have seen from other peoples. And it works for objects but not arrays, it seems to get to the second array, and outputs a string "null"
function fixQuotes($item)
{
if (is_object($item)) {
foreach (get_object_vars($item) as $property => $value) {
//If item is an object, then run recursively
if (is_array($value) || is_object($value)) {
fixQuotes($value);
} else {
$item->$property = htmlentities($value, ENT_QUOTES);
}
}
return $item;
} elseif (is_array($item)) {
foreach ($item as $property => $value) {
//If item is an array, then run recursively
if (is_array($value) || is_object($value)) {
fixQuotes($value);
} else {
$item[$property] = htmlentities((string)$value, ENT_QUOTES);
}
}
}
}
It was not saving the array if it was two arrays deep, it is now working, also it was missing the return on the array. Thanks for reading it.
Here is a copy of the fixed code if someone in future needs a script that does this.
function fixQuotes($item)
{
if (is_object($item)) {
foreach (get_object_vars($item) as $property => $value) {
//If item is an object, then run recursively
if (is_array($value) || is_object($value)) {
$item->$property = fixQuotes($value);
} else {
$item->$property = htmlentities($value, ENT_QUOTES);
}
}
return $item;
} elseif (is_array($item)) {
foreach ($item as $property => $value) {
//If item is an array, then run recursively
if (is_array($value) || is_object($value)) {
$item[$property] = fixQuotes($value);
} else {
$item[$property] = htmlentities((string)$value, ENT_QUOTES);
}
}
return $item;
}
}

Categories