Get key value from multidimensional array not working - php

I am trying to get a value from a multidimensional array by its name 'code'. When I dump and die the first way it returns the correct value. When I then want to use that in the code, it gives the error "Undefined index: code". I also used the array_column way, that dd an empty array.
The code that should get the correct $code:
foreach ($houses as $house) {
$code = $house['code']; //Returns correct value in a dd, not in the code
$code = array_column($house, 'code'); //Returns empty array in dd, later gives the error Array to string conversion in the file_get_contents
$a = file_get_contents('some-url' . $code . '/surveys');
$a = json_decode($a, true);
$surveys = $a['surveys'];
$completedSurveys = $a['surveysCompleted'];
$done = 0;
$ndone = 0;
foreach ($completedSurveys as $complete) {
if($complete) {
$done++;
} else if(!$complete) {
$ndone++;
} else {continue;}
}
}
$house dump:
array:30 [
id: ''
project: integer
city: ''
streetName: ''
houseNumber: ''
code: ''
fullStreet: ''
forms: array:1 [
0: integer
]
]
$code dump
$house['code']: "AB12-CD34-EF56-GH78"
array_column($house, 'code'): []
I would like to know the solution to this so that I can use the $code in the url to get the correct things back from the api.

You can use array_column on your entire array, not the sub-arrays.
$houses =
[
[
'code' => '23',
'city' => 'Dublin'
],
[
'city' => 'Canberra'
],
[
'code' => '47',
'city' => 'Amsterdam'
]
];
var_export(array_column($houses, 'code'));
Output:
array (
0 => '23',
1 => '47',
)
You could then do something along these lines.
$get_survey = function ($code) {
if($response = file_get_contents("http://example.com/$code/surveys"))
if($json = json_decode($response, true))
return $json;
};
$completed = [];
foreach(array_column($houses, 'code') as $code) {
if($survey = $get_survey($code)) {
// survey count calculation.
} else {
$completed[$code] = null; // failure to get survey data.
}
}

Related

check if value exists in multidimensional array and find index

I have an multidimensional array like this:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
I need to check if the value eyetyy exists in this array under the key downloadnaam
Then I need to find the index of this value and remove it from the array.
The expected result:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"]
];
I tried this:
$index = array_search($download->name, array_column($downloadArray, 'downloadnaam'));
if ($index !== null)
{
unset($downloadArray[$index]);
die("found index: " . $index);
}
$download->name contains 'eyetyy'
$downloadArray is my array
But it always dies and doesn't show any index on screen.
Can anyone help me?
Try in this way:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
$filter = "eyetyy";
// Search for index
$index = array_search($filter, array_column($downloadArray, "downloadnaam"));
if ($index !== false) {
// Delete
array_splice($downloadArray, $index, 1);
}
print_r($downloadArray);
die();
Output:
Array
(
[downloads1] Array
(
[downloadnaam] fdgssgsfg
)
)
I got it working using this code
$downloadArray = array_filter($downloadArray, function ($item) use ($download) {
return $item['downloadnaam'] != $download->name;
});
This way I don't need to find the index first.
Credits to #Cositanto
you can try this :
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
foreach ($downloadArray as $subKey => $subArray) {
if (\in_array($subArray['downloadnaam'], ['eyetyy'], true)) {
unset($downloadArray[$subKey]);
}
}
var_dump($downloadArray);
Regards,

How to check index exist or not in my array

I have two arrays
one show all the quiz. another one shows the all taken quiz. now I like o show this for each array that where all quiz list neet to show but match the done quiz table, if available it will return status true. I am using array_key_exist but its showing error.
$getquizId = [
'id' => '',
'title' => '',
'status' => ''
];
$allquizId = [];
$totalQuiz = Quize::where('course_id', $course_id)->with('resources')->get();
$doneQuiz = QuizProgress::where('user_id', $user_id)->where('course_id', $course_id)->with('course')->get();
$progress = (count($doneQuiz) / count($totalQuiz)) * 100;
foreach ($totalQuiz as $key => $value) {
$getquizId = [
'id' => $value->id,
'title' => $value->title,
'status' => (array_key_exists($key, $doneQuiz) ? ($value->id == $doneQuiz[$key]['id'] ? true : false) : false)
];
// if (array_key_exists($key, $doneQuiz)) {
// ($value->id == $doneQuiz[$key]['quiz_id'] ? $getquizId['status'] = 'true' : $getquizId['status'] = 'false');
// }
array_push($allquizId, $getquizId);
}
return $allquizId;
In here (array_key_exists($key, $doneQuiz) ? ($value->id == $doneQuiz[$key]['id'] ? true : false) : false) I need to check the array key exist o not.
I want to show the array like this
[
{
"id": 4,
"title": "Digital Marketing",
"status": true
},
{
"id": 5,
"title": "Personal Leadership",
"status": false
}
]
First get the id of the quiz which is done, and then check the array with in_array
But I would suggest you make the proper relationship
$doneQuiz = QuizProgress::where('user_id', $user_id)->where('course_id', $course_id)->with('course')->pluck('quiz_id')->toArray();
$getquizId = [
'id' => $value->id,
'title' => $value->title,
'status' => in_array($value->id, $doneQuiz) ? true : false
];
Dear always try to do some proper code.
$bool = false;
if(isset($doneQuiz[$key]['id']) && $value->id === $doneQuiz[$key]['id'] )
$bool = true;
put above code before $getquizId array and add $bool variable in value of status.
Note: check the $doneQuiz getting in array format.

Converting string containing multidimensional array keys and values PHP

I use TPP API for check domain availability and domain register but i receive response in string.
Get Session, return stringOK: t73484678463765
Domain check, return string woohoo123.nz: OK: Minimum=1&Maximum=2
In other case, return string woohoo123.nz: ERR: 102, This is message
When It return OK it has & in child but when ERR that time it has ,
I want convert return string into array
such as input woohoo123.nz: OK: Minimum=1&Maximum=2 and output following array
[
'woohoo123.nz' => [
'OK' => [
'Minimum' => 1,
'Maximum' => 2,
]
]
]
input woohoo123.nz: ERR: 102, This is message and output following array
[
'woohoo123.nz' => [
'ERR' => [
'code' => 102,
'message' => 'This is message',
]
]
]
I like more to reuse code, I prefer recursive and callback but not sure in this case.
Not 100% sure if this is what you are looking for. It works for your examples, but will only continue to work if the input strings follow that format strictly.
function stringToArray($inputStr) {
$array = [];
$topComponents = explode(': ',$inputStr);
$parametersStr = $topComponents[count($topComponents) -1];
if (strpos($parametersStr,'&') !== FALSE) {
$tmpArr = explode('&',$parametersStr);
foreach ($tmpArr as $val) {
$comp = explode('=',$val);
$array[$comp[0]] = $comp[1];
}
} else if ($topComponents[count($topComponents) - 2] === "ERR") {
$tmpArray = explode('ERR: ',$parametersStr);
$tmpArray = explode(', ',$tmpArray[0]);
$array = [
"code" => intval($tmpArray[0]),
"message" => $tmpArray[1]
];
} else {
$array = $parametersStr;
}
for ($i=count($topComponents) -2; $i >= 0; $i--) {
$newArray = [];
$newArray[$topComponents[$i]] = $array;
$array = $newArray;
}
return $array;
}
print_r(stringToArray("OK: t73484678463765"));

Dynamic variable name for a multidimentional array

On my left hand I've got this "key" :
localisation.adresse.commune.id
and many other values like this one, wich are dynamics (i can't use them literraly in my code as i don't know what they will be).
On the other hand i have an array like this (comes fron a json decoded) :
Array
(
[localisation] => Array
(
[adresse] => Array
(
[adresse1] => Le Chatelard
[codePostal] => 42820
[etat] => France
[commune] => Array
(
[id] => 16418
)
)
)
)
I can't list all the "keys" i'm going to exploit, so I need to automatically get the value of $object['localisation']['adresse']['commune']['id'].
I've tried this but it does not work :
$test['localisation']['adresse']['commune']['id'] = 16418 ;
$var = '$test[\'localisation\'][\'adresse\'][\'commune\'][\'id\']' ;
echo $var ; // $test['localisation']['adresse']['commune']['id']
var_dump($$var) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
var_dump(${$var}) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
I suppose it's looking for a simple variable of a complicated name, instead of looking at a multidimentional array, but i don't know how i can do it...
Thans for your help !
I see no other way except traversing the array and trying to find the keys in internal arrays, if there are any.
I came up with two variants: recursive and iterative. They will also handle the case when the "depth" of the key and array differ, e.g. if your $key will contain more elements than the depth of the array, then the NULL will be returned, if less - then whatever is under the last key will be returned.
Recursive variant
$a = [
'localisation' => [
'adresse' => [
'adresse1' => 'Le Chatelard',
'codePostal' => 42820,
'etat' => 'France',
'commune' => [
'id' => 16418,
],
],
],
];
$key = 'localisation.adresse.commune.id';
function getValueByKeyRecursively($a, $key)
{
$keyList = explode('.', $key);
$currentKey = array_shift($keyList);
// Found the value
if (empty($currentKey)) {
return $a;
}
// No more depth to traverse or no such key
if (!is_array($a) || !array_key_exists($currentKey, $a)) {
return null;
}
return getValueByKeyRecursively($a[$currentKey], implode('.', $keyList));
}
var_dump(getValueByKeyRecursively($a, $key)); // outputs: int(16418)
Iterative variant
function getValueByKey(array $a, $key)
{
$keyList = explode('.', $key);
$returnValue = $a;
do {
$currentKey = array_shift($keyList);
// Found the value
if ($currentKey === null) {
break;
}
// No more depth to traverse or no such key
if (!is_array($returnValue) || !array_key_exists($currentKey, $returnValue)) {
return null;
}
$returnValue = $returnValue[$currentKey];
} while (true);
return $returnValue;
}
var_dump(getValueByKey($a, $key)); // outputs: int(16418)
try this :
$str = '{
"localisation" : {
"adresse" : {
"adresse1" : "Le Chatelard",
"codePostal" : "42820",
"etat" : "France",
"commune" : {
"id" : 16418
}
}
}
}
';
$data = json_decode($str, true);
$var = $data['localisation']['adresse']['commune']['id'] ;
echo $var ;
print_r($data);

What is the best way to access unknown array elements without generating PHP notice?

If I have this array,
ini_set('display_errors', true);
error_reporting(E_ALL);
$arr = array(
'id' => 1234,
'name' => 'Jack',
'email' => 'jack#example.com',
'city' => array(
'id' => 55,
'name' => 'Los Angeles',
'country' => array(
'id' => 77,
'name' => 'USA',
),
),
);
I can get the country name with
$name = $arr['city']['country']['name'];
But if the country array doesn't exist, PHP will generate warning:
Notice: Undefined index ... on line xxx
Sure I can do the test first:
if (isset($arr['city']['country']['name'])) {
$name = $arr['city']['country']['name'];
} else {
$name = ''; // or set to default value;
}
But that is inefficient. What is the best way to get $arr['city']['country']['name']
without generating PHP Notice if it doesn't exist?
I borrowed the code below from Kohana. It will return the element of multidimensional array or NULL (or any default value chosen) if the key doesn't exist.
function _arr($arr, $path, $default = NULL)
{
if (!is_array($arr))
return $default;
$cursor = $arr;
$keys = explode('.', $path);
foreach ($keys as $key) {
if (isset($cursor[$key])) {
$cursor = $cursor[$key];
} else {
return $default;
}
}
return $cursor;
}
Given the input array above, access its elements with:
echo _arr($arr, 'id'); // 1234
echo _arr($arr, 'city.country.name'); // USA
echo _arr($arr, 'city.name'); // Los Angeles
echo _arr($arr, 'city.zip', 'not set'); // not set
The # error control operator suppresses any errors generated by an expression, including invalid array keys.
$name = #$arr['city']['country']['name'];

Categories