What is the best method to remove commas from numbers in the associative array below? Keep the commas in text, thanks.
$main_arr contains the following 3 arrays:
Array
(
[phrase] => Hi, I'm ok
[number_a] => 3,575
[number_b] => 64
[number_c] => 8,075
)
Array
(
[phrase] => Bye, it's late
[number_a] => 7,365
[number_b] => 32
[number_c] => 648,120
)
Array
(
[phrase] => Good catch!
[number_a] => 11,659
[number_b] => 128
[number_c] => 1,492,352
<?php
$mainArray =[
[
'phrase' => "Hi, I'm ok",
'number_a' => "3,575",
'number_b' => "64",
'number_c' => "8,075",
],
[
'phrase' => "Bye, it's late",
'number_a' => "7,365",
'number_b' => "32",
'number_c' => "648,120",
],
[
'phrase' => 'Good catch!',
'number_a' => "11,659",
'number_b' => "128",
'number_c' => "1,492,352",
],
];
foreach($mainArray as &$array) {
foreach($array as &$val) {
if (preg_match('/^[0-9,]*$/', $val)){
$val = str_replace(',','',$val);
}
}
}
var_export($mainArray);
Related
This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 2 years ago.
I'm trying to get reach a point in a dynamicly generated multidimensional array based on a array with keys.
Basicly I have the following array:
$arr = [
"something" => [
'something_else' => [
"another_thing" => "boo"
]
],
"something2" => [
'something_elseghf' => [
"another_thingfg" => [
"hi" => "bye"
]
]
],
"info" => [
'something_else2' => [
"another_thingh" => "boo"
]
],
];
Now I want to set a value in the array based on the keys in a different array:
$keyArr = ["something2", 'something_elseghf' "another_thingfg", "hi"];
So the above array means that I need to set the hi key to some value. How can I reach that part of the array with these random keys, note that the length of $keyArr is dynamic aswell. So I can't reach it with:
$arr[$keyArr[0]][$keyArr[1]][$keyArr[2]][$keyArr[3]] =
Hope anyone has an idea on how to solve this!
Try this approach:
$arr = [
"something" => [
'something_else' => [
"another_thing" => "boo"
]
],
"something2" => [
'something_elseghf' => [
"another_thingfg" => [
"hi" => "bye"
]
]
],
"info" => [
'something_else2' => [
"another_thingh" => "boo"
]
],
];
$keyArr = ["something2", 'something_elseghf', "another_thingfg", "hi"];
$cursor = $arr;
foreach ($keyArr as $key) {
$cursor = $cursor[$key];
}
echo $cursor;
Will echo
bye
UPDATE:
If you want to change a value within multi-dimentional array, then use a recursive function, like this:
function changeValue($array, $path, $value) {
if (empty($path)) {
return $value;
}
$key = array_shift($path);
$array[$key] = changeValue($array[$key], $path, $value);
return $array;
}
$arr = [
"something" => [
'something_else' => [
"another_thing" => "boo"
]
],
"something2" => [
'something_elseghf' => [
"another_thingfg" => [
"hi" => "bye"
]
]
],
"info" => [
'something_else2' => [
"another_thingh" => "boo"
]
],
];
$keyArr = ["something2", 'something_elseghf', "another_thingfg", "hi"];
$changedArray = changeValue($arr, $keyArr, 'New value!');
print_r($changedArray);
Will output
Array
(
[something] => Array
(
[something_else] => Array
(
[another_thing] => boo
)
)
[something2] => Array
(
[something_elseghf] => Array
(
[another_thingfg] => Array
(
[hi] => New value!
)
)
)
[info] => Array
(
[something_else2] => Array
(
[another_thingh] => boo
)
)
)
Given this example array, with dynamic keys (not known in advance) :
[
["blep" => 32, "blip" => 42],
["blap" => 99, "blep" => null],
["lel" => "hulo"]
]
I would like to be able to get this output :
[
["blap" => null, "blep" => 32, "blip" => 42, "lel" => null],
["blap" => 99, "blep" => null, "blip" => null, "lel" => null],
["blap" => null, "blep" => null, "blip" => null, "lel" => "hulo"]
]
How would I achieve that? Should I just loop over the array elements to get all the keys that exist, then re-loop over those elements to declare the keys that are not declared in the element? Is there no better way?
Thank you !
Try this one.
$collection = collect([
["blep" => 32, "blip" => 42],
["lel" => "hulo"]
]);
$existsKeys = collect(['blap'=>null, 'blep'=>null, 'blip'=>null, 'lel'=>null]);
$newCollection = $collection->map(function($item, $key) use ($existsKeys) {
$diff = $existsKeys->diffKeys($item);
return collect($item)->merge($diff);
});
dd( $newCollection );
For more information please take a look on documentation.
<?php
$array=[
["blep" => 32, "blip" => 42],
["blap" => 99, "blep" => null],
["lel" => "hulo"]
];
$counter=0;
foreach($array as $data){
isset($data['blep'])?true:$array[$counter]['blep']=null;
isset($data['blip'])?true:$array[$counter]['blip']=null;
isset($data['blap'])?true:$array[$counter]['blap']=null;
isset($data['lel'])?true:$array[$counter]['lel']=null;
$counter++;
}
echo '<pre>';
print_r($array);
This code will go through your array and if it finds a value already set will keep it else will add a new array field with the value null. At the end of the loop all the nested array will have the same fields.
Output is:
Array
(
[0] => Array
(
[blep] => 32
[blip] => 42
[blap] =>
[lel] =>
)
[1] => Array
(
[blap] => 99
[blep] =>
[blip] =>
[lel] =>
)
[2] => Array
(
[lel] => hulo
[blep] =>
[blip] =>
[blap] =>
)
)
This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 5 years ago.
Alright, so I'm querying the DB and generating an array from a list of IP addresses:
$q = 'SELECT ip FROM proxy';
$r = mysqli_fetch_all($con->query($q), MYSQLI_ASSOC);
Array returned looks like this:
Array
(
[0] => Array
(
[ip] => 1.202.244.222
)
[1] => Array
(
[ip] => 1.226.238.136
)
[2] => Array
(
[ip] => 1.228.231.247
)
[3] => Array
(
[ip] => 1.238.106.137
)
[4] => Array
(
[ip] => 1.238.155.191
)
But if I want to find say the first or any IP in the above list, for some reason it doesn't find anything:
$ip = "1.202.244.222";
if(in_array($ip,$r)) {
echo "gotcha";
}
What am I doing wrong here?
Got confused by the array within array stuff which I didn't notice at first.
Thanks to Zeth's pointers, I got it to work by collapsing the arrays into one by adding:
$r0 = array_column($r, 'ip');
And then:
if(in_array($ip,$r0)) {
echo "gotcha";
}
It's an array of arrays... Collapse the thing, and then it'll work. There are a couple of options here: How to "flatten" a multi-dimensional array to simple one in PHP?
The most flexible approach for such situations is to use a user defined comparison function:
<?php
$needle = '1.202.244.222';
$haystack = [
[
'ip' => '1.202.244.222'
],
[
'ip' => '1.226.238.136'
],
[
'ip' => '1.228.231.247'
],
[
'ip' => '1.238.106.137'
],
[
'ip' => '1.238.155.191'
]
];
$result = array_filter($haystack, function($entry) use ($needle) {
return isset($entry['ip']) && $needle === $entry['ip'];
});
print_r($result);
The output of above code obviously is:
Array
(
[0] => Array
(
[ip] => 1.202.244.222
)
)
Your Array condition was wrong.
$ip_find = '1.202.244.222';
$ip_values = [
[
'ip' => '1.202.244.222'
],
[
'ip' => '1.226.238.136'
],
[
'ip' => '1.228.231.247'
],
[
'ip' => '1.238.106.137'
],
[
'ip' => '1.238.155.191'
]
];
foreach ($ip_values as $key => $value) {
foreach ($value as $key => $ip) {
if ($ip==$ip_find) {
echo $ip." Gocha";
break;
}
}
}
You can do it using foreach:
$r = [
[
'ip' => '1.202.244.222'
],
[
'ip' => '1.226.238.136'
],
[
'ip' => '1.228.231.247'
],
[
'ip' => '1.238.106.137'
],
[
'ip' => '1.238.155.191'
]
];
$ip = "1.202.244.222";
foreach($r as $elem)
{
if($elem['ip'] == $ip)
{
echo "gotcha";
break;
}
}
I have the following bibliography data in an array (note that fields are in random order - there are others fields as well):
Array
(
[0] => Array
(
['Pub_Name'] => Nature
['Volume'] => 6
['Pages'] => 215-217
)
[1] => Array
(
['Volume'] => 15
['Pages'] => 358-360
['Pub_Name'] => Science
)
[2] => Array
(
['Pub_Name'] => PNAS
['Pages'] => 17-19
['Volume'] => 22
)
)
I want to "merge" those three fields into one, for example ['Pub_Name']=Nature, 6: 215-217. I tried the following whitout success (I guess $Record['Pub_Name'] is the incorrect sintax):
foreach ($MyArray as $Record) {
foreach ($Record as $key => $values) {
if ($key=="Volume") {$Volumen=", ".$values;} else {$Volumen="";}
if ($key=="Pages") {$Paginas=": ".$values;} else {$Paginas="";}
}
//This is the line for which I want to know the sintax!!
$Record['Pub_Name'].=$Volumen.$Paginas;
}
No need for two loops:
foreach ($MyArray as $Record) {
$result[]['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}
Then you have the new Pub_Name entries in $result.
If you want to modify the original then reference & $Record:
foreach ($MyArray as &$Record) {
$Record['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}
Or use the key and modify the original array:
foreach ($MyArray as $key => $Record) {
$MyArray[$key]['Pub_Name'] = "{$Record['Pub_Name']}, {$Record['Pages']}: {$Record['Volume']}";
}
PHP code demo
<?php
$array=Array
(
0 => Array
(
'Pub_Name' => "Nature",
'Volume' => 6,
'Pages' => "215-217"
),
1 => Array
(
'Volume' => 15,
'Pages' => "358-360",
'Pub_Name' => "Science"
),
2 => Array
(
'Pub_Name' => 'PNAS',
'Pages' => "17-19",
'Volume' => 22
)
);
$result=array();
foreach ($array as $data)
{
$result[]=array('Pub_Name'=> $data['Pub_Name'].", ".$data["Volume"].": ".$data["Pages"]);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[Pub_Name] => Nature, 6: 215-217
)
[1] => Array
(
[Pub_Name] => Science, 15: 358-360
)
[2] => Array
(
[Pub_Name] => PNAS, 22: 17-19
)
)
I guess this is what you are looking for:
<?php
$input = [
[
'Pub_Name' => 'Nature',
'Volume' => '6',
'Pages' => '215-217'
],
[
'Volume' => '15',
'Pages' => '358-30',
'Pub_Name' => 'Science',
],
[
'Pub_Name' => 'PNAS',
'Pages' => '17-19',
'Volume' => '22'
]
];
$output = [];
array_walk($input, function ($entry) use (&$output) {
$output[] = sprintf(
'%s, %s: %s',
$entry['Pub_Name'],
$entry['Volume'],
$entry['Pages']
);
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => Nature, 6: 215-217
[1] => Science, 15: 358-30
[2] => PNAS, 22: 17-19
)
Use array_map
$in = [
0 => [
'Pub_Name' => 'Nature',
'Volume' => 6,
'Pages' => '215-217'
],
1 => [
'Volume' => 15,
'Pages' => '358-360',
'Pub_Name' => 'Science',
],
2 => [
'Pub_Name' => 'PNAS',
'Pages' => '17-19',
'Volume' => 22
]
];
array_map(function ($item) {
return $item['Pub_Name'] . ', ' . $item['Volume'] . ': ' . $item['Pages'];
}, $in);
There are a few different ways to do this - but one of the more readable ways:
// create a copy of the original - so we aren't looping thru the same array we're updating
$updatedArray = $MyArray;
foreach ($MyArray as $index => $record) {
$updatedArray[$index]['Pub_Name'] =
$record['Pub_Name'].
($record['Volume'] ? ', '.$record['Volume'] : '').
($record['Pages'] ? ': '.$record['Pages']:'');
}
Clear way in a single loop. Use sprintf() for easy formatting:
<?php
$src =[ ['Pub_Name' => 'Nature', 'Volume' => '6', 'Pages' => '215-217'],
['Volume' => '15', 'Pages' => '358-30', 'Pub_Name' => 'Science'],
['Pub_Name' => 'PNAS', 'Pages' => '17-19', 'Volume' => '22']
];
foreach ($src as $element) {
$dest[] = sprintf("%s, %d: %s",
$element['Pub_Name'],
$element['Volume'],
$element['Pages']);
}
var_dump($dest);
?>
And you get:
array(3) {
[0]=> string(18) "Nature, 6: 215-217"
[1]=> string(19) "Science, 15: 358-30"
[2]=> string(15) "PNAS, 22: 17-19"
}
Test it here.
This should help:
$combined = [];
foreach($myArray as $pub) {
$combined.push($pub['Pub_Name'] . ', ' . $pub['Volume'] . ': ' . $pub['Pages']);
}
I am looping through instances of associative arrays (these associative arrays themselves are part of an array).
For each array I want to return a value, based on a key.
Currently I have:
$image_path = array_column($myarray, 'uri');
But of course array_column stores its values in a array, which, considering it's only returning 1 value, is useless to me.
Is there an existing function that will allow me to just get a value based off a supplied key?
Eg:
$image_path = get_keys_value($myarray, 'uri');
Example array. This is a very basic example. The real thing has many levels to it:
$myarray = array
(
'instance' => array(
'type' => 'somedata',
'content' => somedata',
'image' => array(
'name' => 'photo',
'uri' => 'path/to/file.png'
),
),
);
Desired outcome:
$image_path contains 'path/to/file.png' string.
Try this,
function array_column_recursive(array $haystack, $needle)
{
$found = [];
array_walk_recursive($haystack, function ($value, $key) use (&$found, $needle) {
if ($key == $needle) {
$found[] = $value;
}
});
return $found;
}
echo array_column_recursive($myarray, 'uri')[0];
Here is working code.
array_column will work with only 2 level array structure.
Above array will solve your problem.
I hope this will help
I guess you can use array_map.
Ex:
$arr = [
[
'root' => [
'child1' => [
'child2' => 123
]
]
],
[
'root' => [
'child1' => [
'child2' => 456
]
]
],
[
'root' => [
'child1' => [
'child2' => 789
]
]
],
[
'root' => [
'child1' => [
'child2' => 123
]
]
],
];
print_r(array_map(function($row) {
// here goes expression to get required path
return $row['root']['child1']['child2'];
}, $arr));
Output:
Array
(
[0] => 123
[1] => 456
[2] => 789
[3] => 123
)