Append to an array from a string - php

I've got an array, called $data which needs to be updated with data from an ajax call.
There are two variables sent via an ajax call (with example inputs):
sectionDetails:
[111][0][2][0][service_providers][]
serviceProvider:
Google
The serviceProvider is the data, and the sectionDetails is the array in which the serviceProvider should be in, in the $data array.
What I need is the $data array to end up as:
$data = Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] = Google
)
)
)
)
)
)
This way, I can dynamically input data into any cell and then later I can update specific arrays (e.g. $data[111][0][2][0][service_providers][0] = "Yahoo";
The $_POST['sectionDetails'] is however a string which is where the issue is.
Is there a way to change this string to an array that can then be appended to the main $data array (and in the case of an existing value in the same section, update the value)?
Hope that makes sense.

If you create a function like this:
function setToPath(&$data, $path, $value){
//$temp will take us deeper into the nested path
$temp = &$data;
//notice this preg_split logic is specific to your path syntax
$exploded = preg_split("/\]\[/", rtrim(ltrim($path,"["),"]"));
// Where $path = '[111][0][2][0][service_providers][]';
// $exploded =
// Array
// (
// [0] => 111
// [1] => 0
// [2] => 2
// [3] => 0
// [4] => service_providers
// [5] =>
// )
foreach($exploded as $key) {
if ($key != null) {
$temp = &$temp[$key];
} else if(!is_array($temp)) {
//if there's no key, i.e. '[]' create a new array
$temp = array();
}
}
//if the last index was '[]', this means push into the array
if($key == null) {
array_push($temp,$value);
} else {
$temp = $value;
}
unset($temp);
}
You can use it like this:
setToPath($data, $_POST['sectionDetails'], $_POST['serviceProvider']);
print_r($data) will return:
Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] => Google
)
)
)
)
)
)

Being very careful and depending on the situation, you could use eval:
eval("\$data$sectionDetails = '$serviceProvider';");
print_r($data) will return:
Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] => Google
)
)
)
)
)
)
Caution
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Related

Array values to single array using foreach loop in PHP

I am working with php and arrays, I have multiple arrays like following
Array
(
[0] => Array
(
[wallet_address] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[1] => Array
(
[wallet_address] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[2] => Array
(
[wallet_address] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
and so on....
And i want to make them in single array with comma like following way
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
How can i do this ?Here is my current code but not working,showing me same result(0,1,2 keys),Where i am wrong ?
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[]=$arr;
}
echo "<pre>";print_R($set);
The original array is an Assoc array and therefore the wallet_address needs to be addressed specifically in a loop. Or you could use the array_column() builtin function to achieve the same thing.
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[] = $arr['wallet_address'];
}
echo "<pre>";print_r($set);
Or
$new = array_column($GetUserFollower, 'wallet_address');
print_r($new);
RESULT
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
Your comments are making me think you want an array without a key, which is impossible. If you do this with the example you show in your comments
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
print_r($set);
You will see
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)

Search part of array key on PHP

I have the following output when printing an array called yestardayArray using print_r:
Array
(
[project-id] => Array
(
[373482] => Array
(
[responsible-ids] => Array
(
[171812,129938] => Array
(
[0] => Array
(
[task-id] => 18055196
[content] => HU-002
[responsible-ids] => 171812,129938
)
)
[171812] => Array
(
[0] => Array
(
[task-id] => 18055300
[content] => HU-002
[responsible-ids] => 171812
)
[1] => Array
(
[task-id] => 18055307
[content] => HU-002 - BACK
[responsible-ids] => 171812
)
)
)
)
)
)
I'm iterating througth project-id (using the variable $pid), in the case of this example "373482", and also iterating througth responsible-ids with $key. As $key i'm using all the posible responsible-ids values for the project to get a match and do some stuff.
That work great in the case that there is only one responsible (because there is a full match), but if there are more, like in "171812,129938" there is no match.
How would you validate if $key (171812 or 129938) is part of responsible-ids ("171812,129938")?
I tried to convert the array key to a string, in order to use built-in php search functions like substr_count or strpos.
$needString = $yesterdayArray["project-id"][$pid]["responsible-ids"][$key];
But when I print needString I get "Array" instead of "171812,129938".
What can I do?
Call explode() on the keys, and then use in_array() to check if $key is in the array.
foreach ($yesterdayArray["project-id"] as $pid => $project) {
foreach ($project["responsible-ids"] as $resp_ids => $tasks) {
$resp_id_array = explode(',', $resp_id);
if (in_array($key, $resp_id_array)) {
// do something
}
}
}

Problems changing values in an array/object nested combination array

I don't know what to do to get this done what would like to do. I tried multiple approaches, e.g. I used array_map, array_walk, nested foreach loops with get_object_vars and I worked with json_decode/encode and so on. I always come a little bit further but never reach my goal and I would like to get some guidance from you
Basically when you see the array below, how would you proceed when you want to change some value in the path array for multiple values in the array itself?
My questions:
1) Is it right that I must convert both nested objects to an array first or is this not nesessary to do this? I mean I always get some type conversion error which tells me that I either have everything as an object or array. Is this right?
2) If this mistery is solved, which php array function is the appropriate one to change values in an array(/object)? As I have written above, I tried so many and I don't see the trees in the woods anymore. Which one do you suggest to me to use in a foreach loop?
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
I would suggest that,
you create an array with keys as new path and value as old path (
path to be replaced).
Loop you path array and check if it is available in above defined array.
If available replace it with key of above defined array.
For example
// array defined as point 1
$change_path_array= array('pics'=>'pictures','meal'=>'food');
// $array is your array.
foreach ($array as $value) {
// loop you path array
for($i=0;$i<count($value->doc->path);$i++){
// check if the value is in defined array
if(in_array($value->doc->path[$i],$change_path_array)){
// get the key and replace it.
$value->doc->path[$i] = array_search($value->doc->path[$i], $change_path_array);
}
}
}
Out Put: picture is replaced with pics and food with meal
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pics
[2] => meal
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pics
[2] => vacations
[3] => rome
)
)
)
)
You can modify the code to check casesensitive.
Example of changing all pictures to photos:
$doc1 = new \stdClass;
$doc1->doc = new \stdClass;
$doc1->doc->path = array('Bob', 'pictures', 'food');
$doc2 = new \stdClass;
$doc2->doc = new \stdClass;
$doc2->doc->path = array('Alice', 'pictures', 'vacations', 'rome');
$documents = array($doc1, $doc2);
/* change all 'pictures' to 'photos' */
foreach ($documents as &$doc) {
foreach ($doc->doc->path as &$element) {
if ($element == 'pictures') {
$element = 'photos';
}
unset($element);
}
unset($doc);
}
print_r($documents);
You can do it like this:
for($i = 0; $i < count($arr); $i++){
$path_array = $arr[$i]->doc->path;
// do your modifications for [i]th path element
// in your case replace all 'Bob's with 'Joe's
$path_array = array_map(function($paths){
if($paths == 'Bob') return 'Joe';
return $paths;
}, $paths_array);
$arr[$i]->doc->path = $path_array;
}

Looping through JSON output from Hubspot deals API

I am trying to use the Hubspot API (http://developers.hubspot.com/docs/overview) to loop through all deals and find only those which are current and then do something with those deals.
No matter what I try to do I cannot get my head around how I access the data I need - below is an example of the output.
In the API there are lots of items like dealstage below and the value field under these is what I need to access - for example in this case the deal is closedlost. Another example would be amount which would also have an entry in value so I can then see the deal value.
I want to loop through all deals and for each deal get the dealstage, amount, last update, owner and so on. Each of these are contained in an array of the same layout as [dealstage] below with a value
I have gotten to where I can print the dealstage value for each deal but it doesn't really help - is there a better way of doing this?
foreach ($list['deals'] as $line) {
foreach ($line['properties'] as $row => $value) {
if ($row=="dealstage") {
$stage=$value['value'];
print $stage."<br>";
}
}
}
Example array:
Array
(
[deals] => Array
(
[0] => Array
(
[portalId] => 12345
[dealId] => 67890
[isDeleted] =>
[associations] => Array
(
[associatedVids] => Array
(
[0] => 4051
)
[associatedCompanyIds] => Array
(
[0] => 23456
)
[associatedDealIds] => Array
(
)
)
[properties] => Array
(
[dealstage] => Array
(
[value] => closedlost
)
[createdate] => Array
(
[value] => 1471334633784
)
[amount] => Array
(
[value] => 1000
)
Would something like this be what you are looking for. Loop through the array picking out the items you are interested in and place them in a nice simple array for you to use later when building your email.
$for_email = array();
foreach ($list['deals'] as $line) {
$t = array();
if (isset($line['properties']['dealstage']['value'])) {
$t['dealstage'] = $line['properties']['dealstage']['value'];
}
if (isset($line['properties']['amount']['value'])) {
$t['amount'] = $line['properties']['amount']['value'];
}
if (isset($line['properties']['createdate']['value'])) {
$t['createdate'] = $line['properties']['createdate']['value'];
}
// any other data you want to capture
// put this data in the new array
$for_email[] = $t;
}
// check what the new array looks like
print_r($for_email);

Optimum algorithm to generate keys based on permutations

In my application , I have few parameters (zone_id, startdate, enddate, brand, model) which I get from my UI form . Each of these parameters is an array containing 1 or more parameters .
My form parameters looks something like this :
Array
(
[sel_date_option] => today
[startdate] => 2011-09-19
[enddate] => 2011-09-19
[zone_id] => 1576,1562,1561
[model] => Array
(
[0] => A300
)
[brand] => Array
(
[0] => ACTS
)
)
Now , I want to generate keys which are combinations of these parameters . They would be something like :
[zone_id]_[model]_[brand]_[model]_[startdate]_[enddate]
This reflect all the possible arrangements of the above values .
For the above inputs, I should get the following keys :
1576_ACTS_A300_2011-09-19
1562_ACTS_A300_2011-09-19
1561_ACTS_A300_2011-09-19
Inside of giving the same startdate and enddate once can also enter a period like from 2011-09-19 to 2011-09-21.
What I am doing is I am using nested looping through all the parameter array and then creating a complex array of arrays something like the following :
Array
(
[0] => Array
(
[0] => 1576_DZ_A300
)
[1] => Array
(
[0] => 1576_DZ_A300
[1] => 1562_DZ_A300
)
[2] => Array
(
[0] => 1576_DZ_A300
[1] => 1562_DZ_A300
[2] => 1561_DZ_A300
)
[3] => Array
(
[0] => 1576_DZ_A300
[1] => 1562_DZ_A300
[2] => 1561_DZ_A300
[3] => 1563_DZ_A300
)
)
What I am doing is first I creating an array of all zones as :
Array
(
[0] => 1576
[1] => 1562
[2] => 1561
[3] => 1563
)
Then I am looping it using a nested loop for all the possible models and brands array like this :
function getInventoryData($criteria)
{
$index = "";
if($criteria['zone_id']!='')
{
$zone = explode(',', $criteria['zone_id']);
for($i=0;$i<count($zone);$i++)
{
$index[] .= $zone[$i];
}
echo '<pre>';print_r($index);exit;
}
if(!empty($criteria['model']))
{
foreach($index as $key=>$value)
{
foreach($criteria['model'] as $model)
{
$temparr[] = $index[$key].'_'.$model;
}
$index[$key] = $temparr;
}
}
Now , is there any other efficient method to achieve this ?
Moreover , there is another overhead associated with the above method :
While reading the generated keys , I have to loop through all the levels and in case of large sequence of data , the complexity can be really a matter of concern.
If I understand what you are trying to do correctly, this the most efficient method I can come up with for doing the above:
function getInventoryData ($arr) {
// Make sure all required keys are set
if (!isset($arr['zone_id'],$arr['model'],$arr['brand'],$arr['startdate'],$arr['enddate'])) return FALSE;
// Make a date string for the end of the keys
$dateStr = $arr['startdate'].(($arr['startdate'] == $arr['enddate']) ? '' : '_'.$arr['enddate']);
// Normalise the data
if (!count($arr['zone_id'] = array_unique(explode(',',$arr['zone_id']))) || !count($arr['brand'] = array_unique($arr['brand'])) || !count($arr['model'] = array_unique($arr['model']))) return FALSE;
// Get all possible permutations
$result = array();
foreach ($arr['zone_id'] as $zone) foreach ($arr['brand'] as $brand) foreach ($arr['model'] as $model) $result[] = "{$zone}_{$brand}_{$model}_{$dateStr}";
// Return the result
return $result;
}

Categories