PHP Array Separation - php

I am having a few issues with an array being brought from a database.
The original array once converted looks like this:
Array
(
[0] => {"lastTimeSave":"1494000000"
[1] => "rankexpire":"0"
[2] => "evocity_rank":"g-vip"
[3] => "evocity_rankexpire":"0"}
)
I successfully removed some unuseful characters so my final array looks like this:
Array
(
[0] => lastTimeSave:1494000000
[1] => rankexpire:0
[2] => evocity_rank:g-vip
[3] => evocity_rankexpire:0
)
What I am wanting to do is get everything before the ':' and place it into the key of the array, then remove the ':' so it looks something like this:
Array
(
['lastTimeSave'] => 1494000000
['rankexpire'] => 0
['evocity_rank'] => g-vip
['evocity_rankexpire'] => 0
)
I am separating using:
$staffarray = str_replace('"', "", $staffarray);
$staffarray = str_replace('{', "", $staffarray);
$staffarray = str_replace('}', "", $staffarray);
I have already tried multiple things, including:
foreach ($stafftestarray as $key => $value) {
$substring = substr($value, 0, strpos($value, ';'));
$subsubstring = str_replace($substring, "", $value);
$value = $subsubstring;
}
However nothing seems to change it and the output is not being changed, I would really appreciate any help I can get with this problem as I have searched for countless hours how to fix it to no avail.

Looks like an exploded json object stored as on array.
Though I'm not sure why your data looks like that (did you explode the string by , ?)
This will do what you want:
$data = json_decode(implode(',', $yourArray), true);

Don't remove the " 's and use explode to create a new array based on your old array.
$array = array
(
0 => "lastTimeSave:1494000000",
1 => "rankexpire:0",
2 => "evocity_rank:g-vip",
3 => "evocity_rankexpire:0"
);
$new_array = array();
foreach($array as $value)
{
$item = explode(":", $value);
$new_array[$item[0]] = $item[1];
}
print_r($new_array);
Where print_r($new_array) will give:
Array
(
[lastTimeSave] => 1494000000
[rankexpire] => 0
[evocity_rank] => g-vip
[evocity_rankexpire] => 0
)

Related

PHP Puttin values of array into multidimensional array

Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}

PHP: Better way to replace string value in array with an array?

I'm new to PHP so I'm not sure how to optimize this code.
I execute a Python script from PHP and the $output variable returned is an array of arrays.
exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)
Each array within the $output array contains one string value separated by commas. So $output is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc.
In each array within the $output array, I use explode on the string value to create an array, and add it to my new $output array called $output2
$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}
Is there a way to just replace/overwrite the string value in the arrays within $output with the new array, instead of adding each item to a new $output2 array?
You could use array_walk to do the loop over output. You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array.
Test data:
$output = array(
'1,A,2',
'2,B,3',
'3,C,4'
);
PHP >= 5.3.0
array_walk($output, function(&$val){ $val = explode(',', $val); } );
Older PHP
function mySplit(&$val){
$val = explode(',', $val);
}
array_walk($output, 'mySplit');
Both output:
Array
(
[0] => Array
(
[0] => 1
[1] => A
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => B
[2] => 3
)
[2] => Array
(
[0] => 3
[1] => C
[2] => 4
)
)
Some great answers already. Just adding this for completeness.
$ar = array(
"1,2,3",
"4,5,6"
);
foreach($ar as $k => $v) {
$ar[$k] = explode(',', $v);
}
Wold be interesting to see a a performance difference of the different methods although i doubt it would be much.

str_replace characters PHP

I have this array :
Array
(
[0] => Array
(
[0] => Windows#XP
[1] => 3620
)
[1] => Array
(
[0] => Windows#Vista
[1] => 1901
)
[2] => Array
(
[0] => Windows#7
[1] => 88175
)
and so on...I want to replace # with an space here's my code and it doesnt seem to work:
$tab_os = str_replace('#',' ',$tab_os);
Any solution for that?
Thanks!
You can try this
foreach ($tab_os as $key => $value){
$tab_os[$key] = str_replace('#',' ',$value);
}
but really, str_replace accepts and returns arrays so this shouldn't be the problem. see docs
I have tried and tested this code, try it here: http://codepad.org/Ok1fZ16O
$tab_os = array( array( "Windows#XP", 1 ), array( "Windows#7", 1 ) );
foreach ($tab_os as $key => $value) {
$tab_os[$key] = str_replace('#', ' ', $value);
}
var_dump($tab_os);
Because loops are too mainstream (and also because it's a bit faster), you can use array_map() :
function replaceValue($value) {
return str_replace('#', ' ', $value[0]);
}
array_map('replaceValue', $tab_os);
$tab_os = array(
array('Windows#XP', 3620),
array('Windows#Vista', 1901),
array('Windows#7', 88175),
);
foreach ($tab_os as $os_k => $os_v){
$tab_os[$os_k] = str_replace('#', ' ', $os_v);
}
print_r($tab_os);
You need to loop through it

unique pairs storing in array in php

I am stuck at a scenerio where i need to save user input like... (in 1 go i get these reuslt)
$string = "'a':'php,'b':'.Net' ...
'c' 'java'
'c' 'php'
'c' 'java'
'a' 'php'
'a' 'java' ";
Now i need to store all these values in a database (only unique pairs).
WHat i tried so far, exploded $string with "," and stored everything in an array like
$array["a"] = "php";...but this will overwrite a = java too... //problem
I don't need to check in database that if they exist already or not..this is handled already (all dumped data in one go get a unique identifier).
All i need to do is to get unique pairs and dump into database...means
a = php, a = java, b = .net, c = java, c=php
Only solution i could see was...after exploding ...check for the pair in db against new unique identified...mysql_num_rows...if does not exist then dump else dont...
Is there any easy way...??
The best way for your purpose is to create the multidimensional array
<?php
$string = "'a':'php','b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$array = array();
$temp_arr = explode(",", $string);
foreach($temp_arr as $key=>$value)
{
list($tempkey,$tempValue) = explode(':', $value);
$tempKey = trim($tempkey,"'");
$tempValue = trim($tempValue,"'");
$array[$tempKey][] = $tempValue;
}
$array = array_map('array_unique',$array);
echo "<pre>";
print_r($array);
?>
output will be
Array
(
[a] => Array
(
[0] => php
[2] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)
$string = "'a':'php,'b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$temp = array_map(function($item) {
list($key, $value) = explode(':', $item);
return array(str_replace("'", "", $key) => str_replace("'", "", $value));
}, explode(",", $string));
$results = array();
foreach($temp as $item) {
$key = key($item);
if(!isset($results[$key]) || !in_array($item[$key], $results[$key])) {
$results[$key][] = $item[$key];
}
}
print_r($results);
Output:
Array
(
[a] => Array
(
[0] => php
[1] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Categories