retrieve specific key value from multidimensional array - php

I have the following array, since i converted the string i got back from a SOAP call to an array:
Array
(
[soapenvBody] => Array
(
[queryRequestsResponse] => Array
(
[result] => Array
(
[0] => Array
(
[BCRcustomId] => REQ16569
[BCRexternalId] => Array
(
)
[BCRrecordId] => a035700001CM60kAAD
[BCRrequestId] => a1J5700000857EYEAY
)
[1] => Array
(
[BCRcustomId] => SRQ100784
[BCRexternalId] => Array
(
)
[BCRrecordId] => a033E000001PxfAQAS
[BCRrequestId] => a1J3E0000000GSaUAM
)
)
)
)
)
I am trying to retrieve the BCRrecordId, since I need that item to make another SOAP call. I tried the following
function getID($array) {
return $array['BCRcustomId'];
}
//
$arr = array_map('getID', $array );
print_r($arr);
Now i get an error back on this saying it doesnt find it.
Undefined index: BCRcustomId in
index.php on line 97
[soapenvBody] => )Array (
My assumption is that it doenst go lower than 1 level in the array. Now i am not familair with these kinds of arrays, how would I solve this? By multiple for each loops? Or is there another way to retrieve these items

If $array is the whole response, you need to pass only result part of it:
$arr = array_map('getID', $array['soapenvBody']['queryRequestsResponse']['result']);

Related

Convert large array of array to associative array without loop

I am using aws redis cache for quicker results instead of saving in db.
With this method
$result = $client->listTagsForResource([
'ResourceName' => '<string>', // REQUIRED
]);
Now it gives me result in given format.
Array
(
[0] => Array
(
[Key] => key1
[Value] => string1
)
[1] => Array
(
[Key] => status
[Value] => 1
)
)
I am unable to find a function in amazon docs which can give me direct results, so I decided to search in array , but finding in very large array with loops cost me in terms of time. So is there a way to convert it in following
Array
(
[key1] => string1,
[status] => 1
)
So I can directly access array index by using $array['key1']
You can try something like this to create new array:
$newArray = array_combine(
array_column($array, 'Key'),
array_column($array, 'Value')
);
echo $newArray['status'];

PHP array_merge_recursive with one array

I am struggling with a data structure in PHP. I'm trying to use array_merge_recursive to condense an array by like keys and then grab all values instead of having them overwritten. This is why I chose array_merge_recursive instead of array_merge.
My array is something similar to:
Array
(
[0] => Array
(
[App] => APP1
[Type] => DB
)
[1] => Array
(
[App] => APP1
[Type] => WEBSITE
)
[2] => Array
(
[App] => APP2
[Type] => IOS
)
)
I was expecting array_merge_recursive to combine like keys and then group the other elements into arrays however this is not the behavior I am seeing.
I am hoping to get an array like the following:
Array
(
[0] => Array
(
[App] => APP1
[Type] => Array
(
[0] => DB
[1] => WEBSITE
)
)
[1] => Array
(
[App] => APP2
[Type] => IOS
)
)
array_merge_recursive() does not do what you think it does. You are looking for a function that restructures an array based on specific rules that are helpful to you and as such there isn't a builtin php function for that. I.e. How would PHP know that you wanted to new array to be structured by APP rather TYPE. Assuming your array is always that simple, the easiest version of the function you want looks something like this:
function sortByApp($array){
$result = array();
foreach($array as $row){
if(!isset( $result[ $row['APP'] ] ) {
$result[ $row['APP'] ] = array(
'APP' => $row['APP'],
'TYPE' => array( $row['TYPE'] )
);
}else{
$result[ $row['APP'] ]['TYPE'] = array_merge( $result[ $row['APP'] ]['TYPE'], array($row['TYPE']) );
}
}
$result = array_values($result); //All this does is remove the keys from the top array, it isn't really necessary but will make the output more closely match what you posted.
return $result
}
Note, in this solution, the value of the TYPE key in every APP will always be an array. This makes handling the data later easier in my opinion since you don't have to worry about checking for a string vs an array.

PHP - How to properly merge 2 arrays multi level in this example?

I have the follow array:
$arrIni["ENV"]="US";
$arrIni["sap_db_server"] = "192.xxx.x.xx";
$arrIni["local_db_server"] = "localhost";
$arrIni["local_db_username"] = "root";
//Default settings
$arrIni["arrEnvSettings"]["UserTypeID"]=4;
$arrIni["arrEnvSettings"]["LocalizationID"]=1;
$arrIni["arrEnvSettings"]["LangLabels"] = array();
$arrIni["arrEnvSettings"]["pages"]["st1"]="st1.php";
$arrIni["arrEnvSettings"]["pages"]["st2"]="st2.php";
$arrIni["arrEnvSettings"]["pages"]["st3"]="st3.php";
And I want to merge with this one:
$setParam["arrEnvSettings"]["pages"]["st3"]="st3_V2.php";
This is what I am doing:
echo "<pre>";
print_r(array_merge($arrIni,$setParam));
echo "</pre>";
And this is what I am getting:
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[pages] => Array
(
[st3] => st3_V2.php
)
)
)
In the php doc about merge, this is the comment " ...If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. ..."
So in this way, I suppose to get this output instead of the last one:
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)
[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => st3_V2.php
)
)
)
I do not understand why $setParam["arrEnvSettings"]["pages"]["st3"] is overriding the entire $arrIni["arrEnvSettings"].
Note:
If I use array_merge_recursive($arrIni,$setParam)) I will have the follow result but it is not what I want.
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)
[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => Array
(
[0] => st3.php
[1] => st3_V2.php
)
)
)
)
Is there a way to do this without iterate over the array? Only using merging? What am I doing wrong?
This should do the trick:
array_replace_recursive($arrIni,$setParam);
If you want to merge a given value, use this:
$arrIni["arrEnvSettings"]["pages"]["st3"] = $setParam["arrEnvSettings"]["pages"]["st3"];
But the way you're doing it is merging two arrays, not simply setting the value within an array. There's a gigantic difference between those two methods.
Otherwise, yes you will need to iteratively merge the arrays.
what you need is array_replace_recursive
print_r(array_replace_recursive($arrIni,$setParam));
didnt see the submitted answer..Felippe Duarte has given it already.....

Put a key of end of an array in php

I have this array:
Array
(
[0] => Array
(
[date] => 2016-03-08
[value] => Array
(
[key_1] => Array
(
[test_1] => 1
[test_2] => 10
[test_3] => 1000
[test_4] => 200
)
[key_2] => Array
(
[test_1] => 1
[test_2] => 15
[test_3] => 1500
[test_4] => 100
)
)
)
Now I have another array :
Array
(
[key_3] => Array
(
[test_1] =>
[test_2] =>
[test_3] =>
[test_4] => 1
)
)
I want to add this last array in the first array.
I try like this : array_push($ymlParsedData[]['value'], $a_big_gift); but not work. Can you help me please ?
You can't use $ymlParsedData[] for accessing specific element, it is a shorthand for pushing data to array.
You can use either
// NB! array_push() just adds the values, key 'key_3' is removed
array_push($ymlParsedData[0]['value'], $a_big_gift);
or
// will keep key 'key_3'
$ymlParsedData[0]['value']['key_3'] = $a_big_gift['key_3'];
or
// use array_merge() instead
$ymlParsedData[0]['value'] = array_merge($ymlParsedData[0]['value'], $a_big_gift);
A complicated answer, but this might solve your issue:
$key_name = array_keys($a_big_gift)[0];
$ymlParsedData[0]['value'][$key_name] = $a_big_gift[$key_name];
echo '<pre>'; print_r($ymlParsedData); exit;
Note: For making it dynamic and for more than one value of $a_big_gift, you need to loop it and achieve your result.
Try this
array_push($ymlParsedData[0]['value'], $a_big_gift['key_3']);

Extract specific values from JSON Array php

I have a JSON Array
[0] => Array
(
[stage_id] => 80
[yieldVal] => Array
(
[0] => Array
(
[datajson] => [{"name":"doi","value":"215"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]
)
[1] => Array
(
[datajson] => [{"name":"doi","value":"698"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]
)
)
)
I need to extract the values from this Array
[0] => Array
(
[stage_id] => 80
[yieldVal] => Array
(
[doi_value] => 215
[doi_value] => 698
)
)
I have tried decoding the JSON. But unable to continue further.
$phpArray = json_decode($res['datajson'], true);
How to extract the values and assign the key.
EDIT : My final output should be
[0] => Array
(
[stage_id] => 80
[yieldVal] => 913 //215+698 -> Extracting values from [datajson]
)
One thing that may of tripped you up is that your datajson string is:
`[{"name":"doi","value":"215"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]`
The square brackets mean that json_decode will create an array from the objects.
Anyway, try this...should give you the exact output you asked for:
$yieldVal = 0;
foreach ($res['yieldVal'] as $key => $arr) {
$decode = json_decode($arr['datajson']);
$yieldVal = $yieldVal + $decode[0]->value;
}
$newArray = array (
'stage_id' => $res['stage_id'],
'yieldVal' => $yieldVal
);
//var_dump($newArray);
echo "<pre>".print_r($newArray, true)."</pre>";
You should be able to get the value with:
$doi_value = $phpArray[0]['value'];
You can then sum them, push them onto a resulting array, or whatever.

Categories