I fetch a record from database.
In that I have an array.
$new_val = explode(',',$param->arg_2);
When I var_dump it I get this:
0 => string 'Profile1' (length=8)
1 => string 'Profile2' (length=8)
2 => string 'Profile3' (length=8)
How Can I Get this in var_dump :
Profile1 => string 'Profile1' (length=8)
Profile2 => string 'Profile2' (length=8)
Profile3 => string 'Profile3' (length=8)
After the code:
$new_val = explode(',',$param->arg_2);
Add:
$new_val = array_combine($new_val, array_values($new_val));
Try this
$new_array=array();
foreach($new_val as $nv)
{
$new_array[$nv]=$nv;
}
var_dump($new_array);
Try this:
$array = array('Profile 1', 'Profile 2', 'Profile 3'); //its your exploded string
$newArray = array();
foreach($array as $key => $value)
$newArray[$value] = $value;
var_dump($newArray);
And result is:
array(3) {
["Profile 1"]=>
string(9) "Profile 1"
["Profile 2"]=>
string(9) "Profile 2"
["Profile 3"]=>
string(9) "Profile 3"
}
array_combine — Creates an array by using one array for keys and another for its values
Try this
$array = explode(',',$param->arg_2);
$names = array_combine($array, $array);
var_dump($names);
$arr = array(0 => 'Profile1',
1 => 'Profile2',
2 => 'Profile3');
$vals = array_values($arr);
var_dump(array_combine($vals, $arr));
should output
array(3) { ["Profile1"]=> string(8) "Profile1" ["Profile2"]=> string(8) "Profile2" ["Profile3"]=> string(8) "Profile3" }
While searching thorught PHP guide I came across this and eve this helped me:
eval("\$new_val = array (".$param->arg_2.");");
Related
Here is what it looks like after getting value from CDATA via simplexmlelement
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}"
I tried looking into solutions in google but i am not able to find one which would convert this set of strings to array.
I want this data to convert into array something like this
["customertype"] = ["New"]
["Telephone"] = ["09832354544"]
so and so forth or something similar as how array looks like.
Thanks in advance
Given your data string format, you may do as follows:
First of all, remove the brackets { }
Then explode the string using the , delimiter.
Now, you have array of strings containing for example customertype=New.
Next is the tricky part, the result string looks like a query, so we're gonna use
parse_str() to make an associative array:
The result will be something similar to this:
array:9 [▼
0 => array:1 [▼
"customertype" => "New"
]
1 => array:1 [▼
"Telephone" => "09832354544"
]
2 => array:1 [▼
"CITY" => "Henfield"
]
And here's the code:
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$rippedData = str_replace(["{", "}"],"", $data);
$singleData= explode(",", $rippedData);
$finalArray = [];
foreach($singleData as $string){
parse_str($string, $output);
$finalArray[] = $output;
}
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$stripped = str_replace(['{','}'], '', $data);
$explode = explode(', ', $stripped);
$output = [];
foreach ($explode as $value) {
$inner_explode = explode('=', $value);
$output[$inner_explode[0]] = $inner_explode[1];
}
var_dump($output);
Results in
array(9) {
["customertype"]=>
string(3) "New"
["Telephone"]=>
string(11) "09832354544"
["CITY"]=>
string(8) "Henfield"
["LASTNAME"]=>
string(1) "C"
["TicketNo"]=>
string(6) "123456"
["FIRSTNAME"]=>
string(4) "Alex"
["Id"]=>
string(8) "10001273"
["testfield"]=>
string(6) "123456"
["COMPANY"]=>
string(5) "Camp1"
}
This should work, though there's probably a better/cleaner way to code this.
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
// Replace squiggles
$replace_this = array("{","}");
$replace_data = str_replace($replace_this,"",$data);
// Explode and create array
$data_array = explode(',',$replace_data);
// Loop through the data_array
foreach($data_array as $value) {
// Explode the value on the equal sign
$explode_again = explode('=', $value);
// Create new array with correct indexes and values
$CDTA[trim($explode_again[0])] = $explode_again[1];
}
echo '<pre>' . var_export($CDTA, true) . '</pre>';
Result:
array (
'customertype' => 'New',
'Telephone' => '09832354544',
'CITY' => 'Henfield',
'LASTNAME' => 'C',
'TicketNo' => '123456',
'FIRSTNAME' => 'Alex',
'Id' => '10001273',
'testfield' => '123456',
'COMPANY' => 'Camp1',
)
I did this from the database.
how to find the the $dependency separator after explode i want explode that array .
$dependency = 2/3&3/6;
$find = explode('&',$dependency);
string(7) "2/3&3/6"
I am getting like,
sarray(2) {
[0]=>string(3) "2/3"
[1]=>string(3) "3/6"
}
But i want the result to be like this:
sarray(2) {
[0]=>array(2) {
[0]=>string(1) "2"
[1]=>string(3) "3"
}
[1]=>array(2) {
[0]=>string(1) "3"
[1]=>string(3) "6"
}
}
please help to find the this array separator.
You need read the array using foreach then explode again to get the desired result.
$dependency = '2/3&3/6';
$find = explode('&',$dependency);
$result = array();
foreach($find as $val){
$result = array_merge($result,explode("/",$val));//Store all the values in one array
or
$result[]=explode("/",$val); //store array as key
}
var_dump($result);
Here you go first explode with '&' then with '/' on each array item
$str = "2/3&3/6";
$arr= explode('&',$str);
foreach($arr as $val){
$arrData[]= explode('/',$val);
}
echo "</pre>";
print_r($arrData);
You have to further use foreach to separate string again
$dependency = "2/3&3/6";
$find = explode('&',$dependency);
$new_array=array();
foreach ($find as $key => $value) {
$new_array[]=explode('/',$value);
}
var_dump($new_array);
OUTPUT:
array (size=2)
0 =>
array (size=2)
0 => string '2' (length=1)
1 => string '3' (length=1)
1 =>
array (size=2)
0 => string '3' (length=1)
1 => string '6' (length=1)
So recently I got stuck in some sort of array combine and replace situation.
I had this array:
array(5) {
["De"]=>
string(7) "treatee"
["Para"]=>
string(13) "Cristina Isabel Gnap"
["Principio"]=>
string(36) "Agilidade, como dinâmica de ação."
["Descricao"]=>
string(8) "sadsadsa"
}
I wanted to remove the middle name from ['Para'] field so I made a for loop like this:
for ($i = 0; $i < count($rows); $i++) {
$array = explode(' ', $rows[$i]['Para']);
$firstName = $array[0];
$lastName = $array[count($array) - 1];
$combineNames= $primeiroNome." ".$ultimoNome;
$namesCombined= str_split($combineNomes, 30);
$result = array_replace($rows[$i], $nomesArray);
}
The result of course, display this:
array(5) {
["De"]=>
string(7) "treatee"
["Para"]=>
string(20) "Cristina Isabel Gnap"
["Principio"]=>
string(36) "Agilidade, como dinâmica de ação."
["Descricao"]=>
string(8) "sadsadsa"
["0"]=>
string(13) "Cristina Gnap"
}
But what I actually need to do, is to replace the ["Para"] field with the new ["0"] field, but it seems when I put in the for something like $result = array_replace($rows[$i]['Para'], $nomesArray); it returns this:
Warning: array_replace(): Argument #1 is not an array
Can anyone help me? =D
To iterate over an array you can use a foreach loop. $row is prefixed with an & so that any changes you make will be applied to the original array (passing by reference).
foreach ($rows as &$row) {
$original_string = $row['Para'];
// make your changes here and assign the new value to $new_string
$row['Para'] = $new_string;
}
For reference,
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/language.references.pass.php
Please use unset() function
$array = array {
["De"]=>
string(7) "treatee"
["Para"]=>
string(13) "Cristina Isabel Gnap"
["Principio"]=>
string(36) "Agilidade, como dinâmica de ação."
["Descricao"]=>
string(8) "sadsadsa"
}
unset($array['pra']);
You can use a combination of preg_split and foreach loop to achieve as shown below. By the way, you can test the result here:
<?php
$arr = [
"De" =>"treatee",
"Para" => "Cristina Isabel Gnap",
"Principio" =>"Agilidade, como dinâmica de ação.",
"Descricao" =>"sadsadsa",
];
var_dump($arr);
foreach($arr as $key=>&$value){
if($key == "Para"){
if(is_string($value)) {
$arrSplits = preg_split("#\s#", $value);
if (count($arrSplits) == 3) {
unset($arrSplits[1]);
$arr[$key] = implode(" ", $arrSplits);
}
}
}
}
var_dump($arr);
RESULT OF 1ST VAR_DUMP
array (size=4)
'De' => string 'treatee' (length=7)
'Para' => string 'Cristina Isabel Gnap' (length=20)
'Principio' => string 'Agilidade, como dinâmica de ação.' (length=42)
'Descricao' => string 'sadsadsa' (length=8)
RESULT OF 2ND VAR_DUMP
array (size=4)
'De' => string 'treatee' (length=7)
'Para' => string 'Cristina Gnap' (length=13)
'Principio' => string 'Agilidade, como dinâmica de ação.' (length=42)
'Descricao' => string 'sadsadsa' (length=8)
Alternatively, You could encapsulate the above into a Function that accepts an Array and pass-in your array like so:
<?php
function removeMiddleNamesFromArray(&$dataArray){
foreach($dataArray as $key=>&$value){
if($key == "Para"){
if(is_string($value)){
$arrSplits = preg_split("#\s#", $value);
if( count($arrSplits) == 3){
unset($arrSplits[1]);
$arr[$key] = implode(" ", $arrSplits);
}
}
}
}
return $dataArray;
}
var_dump(removeMiddleNamesFromArray($arr));
DUMPS
array (size=4)
'De' => string 'treatee' (length=7)
'Para' => string 'Cristina Gnap' (length=13)
'Principio' => string 'Agilidade, como dinâmica de ação.' (length=42)
'Descricao' => string 'sadsadsa' (length=8)
Alternatively, You could encapsulate the above into a Function that accepts an Array and pass-in your array like so:
Here is a var_dump of my array:
array(6) {
[0]=> string(4) "quack"
["DOG"]=> string(4) "quack"
[1]=> string(4) "quack"
["CAT"]=> string(4) "quack"
[2]=> string(4) "Aaaaarrrrrggggghhhhh"
["CAERBANNOG"]=> string(4) "Aaaaarrrrrggggghhhhh"
}
(just for fun I've included two puns in this code, try and find them!)
How do I split this array into two arrays, one containing all the quacks; the other Aaaaarrrrrggggghhhhh?
Note that it won't always be in consecutive order, so was thinking maybe nested hashmaps, something like:
Check if (isset($myarr['$found_val']))
Append that array if found
Else create that place with a new array
But not sure how the arrays are implemented, so could be O(n) to append, in which case I'd need some other solution...
You can just group them based on values and store the keys
$array = array(0 => "quack","DOG" => "quack",1 => "quack","CAT" => "quack",2 => "Aaaaarrrrrggggghhhhh","CAERBANNOG" => "Aaaaarrrrrggggghhhhh");
$final = array();
foreach ( $array as $key => $value ) {
if (! array_key_exists($value, $final)) {
$final[$value] = array();
}
$final[$value][] = $key;
}
var_dump($final);
Output
array
'quack' =>
array
0 => int 0
1 => string 'DOG' (length=3)
2 => int 1
3 => string 'CAT' (length=3)
'Aaaaarrrrrggggghhhhh' =>
array
0 => int 2
1 => string 'CAERBANNOG' (length=10)
Try this
$quacks_arr = array_intersect($your_array, array('quack'));
$argh_arr = array_intersect($your_array, array('Aaaaarrrrrggggghhhhh'));
If you want to sort them, then just do ksort
ksort($quacks_arr);
ksort($argh_arr);
Just in case anyone wants to do this in a more of and odd way:
Updated with air4x's idea of using only a single item array, instead of array_fill(0,count($a),$v). Makes it's much more sensible.
$a = array(
0 => "quack",
"DOG" => "quack",
1 => "quack",
"CAT" => "quack",
2 => "Aaaaarrrrrggggghhhhh",
"CAERBANNOG" => "Aaaaarrrrrggggghhhhh"
);
$b = array();
foreach( array_unique(array_values($a)) as $v ) {
$b[$v] = array_intersect($a, array($v));
}
echo '<xmp>';
print_r($b);
Totally not optimal - difficult to read - but still interesting :)
I'm programming in php for years, but i have encountered a redicilous problem and have no idea why it has happened. I guess i'm missing something, but my brain has stopped working!
I have an ass. array and when i var_dump() it, it's like this:
array
0 =>
array
4 => string '12' (length=2)
1 =>
array
2 => string '10' (length=2)
2 =>
array
1 => string '9' (length=1)
I want to do something with those values like storing them in an array, (12, 10, 9), but I dont know how to retrieve it! I have tested foreach(), array_value(), but no result. No matter what i do, the var_dump() result is still the same!
by the way i'm using codeigniter framework, but logically it should have nothing to do with the framework
thanks guys
You can try using array_map
$array = array(
0 => array(4 => '12'),
1 => array(2 => '10'),
2 => array(1 => '9'));
$array = array_map("array_shift", $array);
var_dump($array);
Output
array
0 => string '12' (length=2)
1 => string '10' (length=2)
2 => string '9' (length=1)
You can access them like this:
$array[0][4]= '13';
$array[1][2]= '11';
$array[2][1]= '10';
var_dump($array); gives this result:
array(3) {
[0]=> array(1) {
[4]=> string(2) "13" }
[1]=> array(1) {
[2]=> string(2) "11" }
[2]=> array(1) {
[1]=> string(2) "10" }
}
like this:
for ($i = count($array) ; $i >= 0 ; $i--) {
foreach($array[$1] as $k => $v) {
echo $k . "=>".$v;
}
}
If you want them to end up in an array, declare one, then iterate over your items.
$arr = new array();
foreach ($arrItem in $yourArray) {
foreach ($innerArrItem in $arrItem) {
array_push($arr, $innerArrItem);
}
}
print_r($arr);
If you have an unknown depth, you can do something like this:
$output = array();
array_walk_recursive($input, function($value, $index, &$output) {
$output[] = $value;
}, $output);