PHP Array Replace Issue - php

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:

Related

Expload Separator Array

I have an code from database like
$exp = ukuran:33,34,35;warna:putih,hitam;
i want to make an array like
$ukuran = array("33", "34", "35");
$warna = array("putih","hitam");
i have try to use explode but i have trouble result.
explode(";",$exp);
the result like
Array
(
[0] => ukuran:33,34,35
[1] => warna:putih,hitam
[2] =>
)
Anyone can help me, how to explode this case please?
$string = 'ukuran:33,34,35;warna:putih,hitam;';
$string = str_replace(['ukuran:', 'warna:'], '', $string);
$exploded = explode(';', $string);
$ukuran = explode(',', $exploded[0]);
$warna = explode(',', $exploded[1]);
If you want to do it dynamically you can't create variables but you can create an array with the types as keys:
$string = 'ukuran:33,34,35;warna:putih,hitam;';
$exploded = explode(';', $string);
$keysAndValues = [];
foreach($exploded as $exp) {
if (strlen($exp) > 0) {
$key = substr($exp, 0, strpos($exp, ':' ) );
$values = substr($exp, strpos($exp, ':' ) + 1, strlen($exp) );
$values = explode(',', $values);
$keysAndValues[$key] = $values;
}
}
This will output:
array (size=2)
'ukuran' =>
array (size=3)
0 => string '33' (length=2)
1 => string '34' (length=2)
2 => string '35' (length=2)
'warna' =>
array (size=2)
0 => string 'putih' (length=5)
1 => string 'hitam' (length=5)
Call them like this:
var_dump($keysAndValues['ukuran']);
var_dump($keysAndValues['warna']);
I would personally say continue as you are, then with your array in your result, loop through each item in the array and store it like so
$string = 'ukuran:33,34,35;warna:putih,hitam;';
$exploded = explode(';',$string);
$master = [];
foreach($exploded as $key => $foo){
$namedKey = explode(':',$foo);
$bar = substr($foo, strpos($foo, ":") + 1); //Get everything after the ; character
$master[$namedKey[0]] = explode(",",$bar);
}
This should return a result something along the lines of
array(3) {
["ukuran"]=>
array(3) {
[0]=>
string(2) "33"
[1]=>
string(2) "34"
[2]=>
string(2) "35"
}
["warna"]=>
array(2) {
[0]=>
string(5) "putih"
[1]=>
string(5) "hitam"
}
}
You can use regex to match words and numbers separate.
Then use array_filter to remove the empty values.
$exp = "ukuran:33,34,35;warna:putih,hitam";
Preg_match_all("/(\d+)|([a-zA-Z]+)/", $exp, $matches);
Unset($matches[0]);
$matches[1] = array_filter($matches[1]);
$matches[2] = array_filter($matches[2]);
Var_dump($matches);
https://3v4l.org/cREn7
Actually there are many ways to do what you want, But If I were you then I'll try this way :)
<?php
$exp = 'ukuran:33,34,35;warna:putih,hitam';
$result = explode(';',$exp);
foreach($result as $k=>$v){
$key_value = explode(':',$v);
// this line will help your to treat your $ukuran and $warna as array variable
${$key_value[0]} = explode(',',$key_value[1]);
}
print '<pre>';
print_r($ukuran);
print_r($warna);
print '</pre>';
?>
DEMO: https://3v4l.org/BAaCT

How to name array elements in PHP?

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.");");

PHP - group every 2 parts of a string together in an array

I have a long string that is constructed like this:
randomstring number randomstring number randomstring number
I need to group these random strings and numbers together so that I get an array like this:
array = [[randomstring, number], [[randomstring, number], [randomstring, number]]
I don't know the amount of spaces between the strings and numbers. Any suggestions?
UPDATE
Since Edwin Moller's answer I'm now left with this array:
Array (46) {
[0] =>
array(2) {
[0]=>
string(20) "string"
[1]=>
string(7) "number"
}
[1]=>
array(2) {
[0]=>
string(5) ""
[1]=>
string(7) ""
}
[2] =>
array(2) {
[0]=>
string(10) ""
[1]=>
string(11) ""
}
[3] =>
array(2) {
[0]=>
string(10) ""
[1]=>
string(11) ""
}
[4] =>
array(2) {
[0]=>
string(10) ""
[1]=>
string(11) ""
}
The array elements that have 2 empty elements themselves need to be removed.
I'll leave it with this solution. It's not elegant at all, but I don't know what these 'empty' strings are. It doesn't respond to whitespace, space, any character test so I used the strlen() function:
$str = preg_replace('!\s+!', ' ', $longstring);
$parts = explode(" ", $str);
$nr = count($parts);
for ($i = 0; $i < $nr; $i = $i + 2) {
if(strlen($parts[$i]) > 20) { // ugly, but it works for now..
$tmp[] = [$parts[$i], $parts[$i + 1]];
}
}
// unsetting these elements because they are longer than 30
unset($tmp[0]);
unset($tmp[1]);
unset($tmp[2]);
$longstring = "randomstring1 1001 randomstring2 205 randomstring3 58";
// First, take care of the multiple spaces.
$str = preg_replace('/\s+/', ' ', $longstring);
// split in parts on space
$parts = explode(" ",$str);
$nr = count($parts);
$tmp = array();
for ($i=0; $i<$nr; $i=$i+2){
$tmp[] = array($parts[$i], $parts[$i+1]);
}
echo "<pre>";
print_r($tmp);
echo "</pre>";
You might want to make sure it is an even number. (check $nr).
Edit: OP says you have some empty elements in the array $parts.
I don't know what causes that, possibly some encoding issues, not sure without having the original material (string).
A wild guess: Try to utf8_decode the original string, then do the preg_replace, and then print_r.
Like this:
$longstring = "randomstring1 1001 randomstring2 205 randomstring3 58";
$longstring = utf8_decode($longstring);
$str = preg_replace('/\s+/', ' ', $longstring);
$parts = explode(" ",$str);
echo "<pre>";
print_r($parts);
echo "</pre>";
explode string and then check it like this
Online Demo
$str="randomstring number randomstring number randomstring number";
$exp=explode(" ",$str);
for($i=0;$i<count($exp);$i++)
{
if(trim($exp[$i])=="")
continue;
$result[]=array(0=>$exp[$i],1=>$exp[$i+1]);
$i++;
}
var_dump($result);
Try the following
//Our string
$string = "randomstring 11 randomstring 22 randomstring 33";
//Split them up if they have MORE THAN ONE space
$firstSplit = preg_split('/\s\s+/', $string);
//Set up a new array to contain them
$newArray = array();
//For each of the ones like "randomstring 11"
foreach($firstSplit as $key => $split){
//Split them if they have ONE OR MORE space
$secondSplit = preg_split('/\s+/', $split);
//Add them to the array
//Note: change this part to structure the array however you'd like
$newArray[$key]["string"] = $secondSplit[0];
$newArray[$key]["integer"] = $secondSplit[1];
}
The comments should explain well enough what is happening here, it will leave you with the following:
array (size=3)
0 =>
array (size=2)
'string' => string 'randomstring' (length=12)
'integer' => string '11' (length=2)
1 =>
array (size=2)
'string' => string 'randomstring' (length=12)
'integer' => string '22' (length=2)
2 =>
array (size=2)
'string' => string 'randomstring' (length=12)
'integer' => string '33' (length=2)
I do not know if it is the shortest way but i would say your issue can be consist of this steps
1- convert the multi spaces to one space
2- explode the big string to one array has all the sub string
3- group the elements by loop over the big array
<?php
$str = 'randomstring1 number1 randomstring2 number2 randomstring3 number3';
//remove the spaces and put all the element in one array
$arr = explode(' ', $str);
$space = array('');
$arr = array_values(array_diff($arr, $space));
//now loop over the array and group elements
$result = $temArr = array();
foreach($arr as $index => $element){
if($index % 2){//second element (number)
$temArr[] = $element;
$result[] = $temArr;
$temArr = array();
}else{//first element (randomstring)
$temArr[] = $element;
}
}
//print the result
var_dump($result);die;
?>
First split by 2 or more spaces, then split those groups by the single space.
Try this:
$input = 'randomstring1 number1 randomstring2 number2 randomstring3 number3';
$groups = preg_split("/[\s]{2,}/", $input );
$result = array_map(function($i){
return explode(' ', $i);
}, $groups);
Which gets me this result:
array(3) {
[0] = array(2) {
[0] = string(13) "randomstring1"
[1] = string(7) "number1"
}
[1] = array(2) {
[0] = string(13) "randomstring2"
[1] = string(7) "number2"
}
[2] = array(2) {
[0] = string(13) "randomstring3"
[1] = string(7) "number3"
}
}

PHP var_dump and loop giving different results

I have the following code:
var_dump($cursor);
foreach($cursor as $obj) {
echo "<div class='item' id='" . $obj['_id'] . "'>";
echo "<span class='listnick'>" . $obj['nick'] . "</span>";
echo "</div>";
}
The result of var_dump is the following:
array(2) {
[0]=>
&array(9) {
["_id"]=>
object(MongoId)#9 (1) {
["$id"]=>
string(24) "50af8dcd9cc231534400000c"
}
["nick"]=>
string(6) "safari"
}
[1]=>
array(9) {
["_id"]=>
object(MongoId)#8 (1) {
["$id"]=>
string(24) "50af8dca9cc2315644000009"
}
["nick"]=>
string(6) "chrome"
}
}
so obviously the foreach should print out "safari" and "chrome", but the problem is really weird:
Sometimes it returns "safari" twice and omits "chrome", and viceversa for the other client. I tried putting the var_dump and the foreach loop near to be sure they are the SAME and there are no changes in the object between the two commands, but really I got no idea what's going on.
Any help? Thanks in advance.
Notice how safari is a reference to an array: &array.
This might result from having a foreach where $obj is a reference:
foreach($cursor as &$obj) {
..
}
//unset($obj);
In PHP, the scope of $obj does not end with execution of the loop, so you should do an unset whenever you looped using a reference.
This might also result from using the reference assignment somewhere:
$cursor[] =& $safari;
This are 2 difference codes ... One is using & reference which would modify the array output and the other is not
array(2) {
[0]=>
&array(9) {
^----------------------------- Reference sign
["_id"]=>
object(MongoId)#9 (1) {
["$id"]=>
string(24) "50af8dcd9cc231534400000c"
}
["nick"]=>
string(6) "safari"
}
Topical example of what happened
$a = $b = array(array("_id" => new MongoId(),"nick" => "chrome"));
foreach ( $a as $k => &$v )
$k == "nick" and $v['nick'] = "Safari";
foreach ( $b as $k => $v )
$k == "nick" and $v['nick'] = "Safari";
var_dump($a);
var_dump($b);
Output
array (size=1)
0 =>
&array (size=2)
'_id' =>
object(MongoId)[1]
public '$id' => string '50af93a2a5d4ff5015000011' (length=24)
'nick' => string 'Safari' (length=6) <------ changed
array (size=1)
0 =>
array (size=2)
'_id' =>
object(MongoId)[2]
public '$id' => string '50af93a2a5d4ff5015000012' (length=24)
'nick' => string 'chrome' (length=6) <------- not changed
Can you see that one if the Nick is modified not the two

getting values from associative arrays in php

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);

Categories