I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"]; is working well, but echo $array["Peter"]; is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
You'll have to go in two steps :
First, explode using ', ', as a separator ; to get pieces of data such as "Peter"=>32
And, then, for each value, explode using '=>' as a separator, to split the name and the age
Removing the double-quotes arround the name, of course.
For example, you could use something like this :
$result = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(', ', $ages2) as $couple) {
list ($name, $age) = explode('=>', $couple);
$name = trim($name, '"');
$result[$name] = $age;
}
var_dump($result);
And, dumping the array, you'd get the following output :
array
'Peter' => string '32' (length=2)
'Quagmire' => string '30' (length=2)
'Joe' => string '34' (length=2)
Which means that using this :
echo $result['Peter'];
Would get you :
32
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
$array = eval('return array('.$ages2.');');
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
You'll need to build the array yourself by extracting the name and age:
<?php
$array = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(",", $ages2) as $element) {
$parts = explode("=>", $element);
if (count($parts) == 2) {
$name = str_replace(array('"', ' '), '', $parts[0]);
$age = (int) $parts[1];
$array[$name] = $age;
}
}
print_r($array);
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$items = explode(",", $ages2);
foreach ($items as $item) {
list($key,$value) = explode('=>',$item);
$key = str_replace('"','',trim($key)); // Remove quotes and trim whitespace.
$array[$key] = (int)$value;
}
If you var_dump($array), you'll have:
array(3) {
["Peter"]=>
int(32)
["Quagmire"]=>
int(30)
["Joe"]=>
int(34)
}
So you can do this as expected and get 32 back out:
echo $array['Peter']
Related
I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);
So my question might not be the best, so sorry for that.
I have an array with strings and want to write a text with the help of another array using it as the order/key. This is the Input:
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
//var_export($words);
// array (
// 0 => 'I',
// 1 => 'am',
// 2 => 'cool',
// )
I want to use $order as some sort of key to rearrange $words so I can get this Output:
"Cool I am I am cool"
Help is much appreciated, thank you :)
Use the values of $order as the keys for $words.
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
$output = '';
foreach($order as $key) {
$output .= $words[$key] . ' ';
}
echo ucfirst(trim($output));
Demo: https://eval.in/780785
The empty($real_key) is to check if it is the first iteration. Also could be == 0.
I would recommend the use of array_map and join
There is no need for
side-effecting manual iteration using foreach
if statements or ternary (?:) expressions
variable reassignment
string concatenation using .
checking array lengths
Here we go
function map_indexes_to_words ($indexes, $words) {
$lookup = function ($i) use ($words) {
return $words[(int) $i];
};
return join(' ', array_map($lookup, $indexes));
}
$words = ["I","am","cool"];
$order = ["2","0","1","0","1","2"];
echo map_indexes_to_words($order, $words);
// 'cool I am I am cool'
Start with an empty array.
Then loop through the order array and add the word array part to the new string.
$my_string= array();
foreach ( $order as $index ) {
$index = int($index);
$my_string[] = ( isset($words[ $index]) ) ? $words[ $index ] : '' );
}
$my_string = implode(' ', $my_string);
echo my_string;
Iterate over order and use it's values as keys to words; Convert the following code to php it should be pretty simple...
foreach (string orderIndexString in order) {
int orderIndexInt = System.Convert.ToInt16(orderIndexString); // convert string to int
if(orderIndexInt < 0 || orderIndexInt >= words.Length)
continue;
print (words[orderIndexInt]); // either print or add it to another string
}
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.
I'm not sure how to better phrase my question, but here is my situation.
I have an array like the following:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
I need to loop through this array and try to match the first portion of each string in the array
e.g.
$id = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
fetch this string
append "999888" to "122874|876394|120972"
insert this string back to array
}
So the resulting array becomes:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");
Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.
Thanks
Try this:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){
// Get the first characters of the element up to the occurrence of a dash "-" ...
$num = substr($arr, 0, strpos($arr, '-'));
// ...and check if it is equal to $id...
if ($num == $id){
// ...if so, add $random_number to the back of the current array element
$temp_array[$i] .= '|' . $rand_number;
}
}
Output:
Array
(
[0] => 111111-Name1-122874|876394|120972
[1] => 222222-Name2-122874|876394|120972|999888
[2] => 333333-Name3-122874|876394|120972
)
See demo
Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php
You could also using some exploding in this case too:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
// ^ reference
$pieces = explode('|', $line); // explode pipes
$first = explode('-', array_shift($pieces)); // get the first part, explode by dash
if($first[0] == $id) { // if first part is equal to id
$first[2] = $rand_number; // replace the third part with random
$first = implode('-', $first); // glue them by dash again
$line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
}
}
echo '<pre>';
print_r($temp_array);
crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr
$temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as $t){
if(substr(0,6,$t)==$id){
$new[] = $t.'|'.$rand_number;
}else{
$new[] = $t;
}
}
Another version using array_walk
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
$parts = explode('-', $value); // Split parts with '-' so the first part is id
if ($parts[0] == $param['id']){
$parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
$value=implode('-',$parts); //combine the parts back
}
},$params);
print_r($temp_array);
If you just want to append The code becomes much shorter
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
// here check if the first part of the result of explode is ID
// then append the rand_number to the value else append '' to it.
$value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);
Edit: Comments added to code.
I have two issues I was hoping to get help on:
Combine two arrays into one string
and add some formatting
insert the new string into a
specific spot in a bigger string.
I have two arrays:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
foreach ($result as $val){
//NEED HELP HERE create a string that adds a "mac=" to the beginning of the current $val and adds a "/n" to the end of the current value.
}
The above should somehow create the string below:
$my_string = "mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n";
Now for Part #2
I have a current string that was created already:
$current_String = "[MACS]/n
mac=blah1/n
mac=blah2/n
mac=blah3/n
[SERVICES]";
My last issue is to replace everything between [MACS]/n and [SERVICES] with $my_string
So I should end up with:
$updated_String = "[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]";
Any help or insight would be greatly appreciated.
This should work:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
$myString = "[MACS]/n\nmac=" . implode($result, "/n\nmac=") . "/n\n[SERVICES]";
//replace in other string
$macsIndex = strrpos($currentString, "[MACS]");
$servicesIndex = strrpos($currentString, "[SERVICES]");
$currentString = substr($currentString, 0, $macsIndex) . $myString . substr($currentString, servicesIndex+10);
Outputs:
[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]
$formatted = '';
foreach ($result as $val){
$val = sprintf("mac=%s\n", $val);
$formatted .= $val;
}