getting values from associative arrays in php - 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);

Related

How to separate the operator inside the array?

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)

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 Array Merge two Arrays on same key

I am trying to merge the following two arrays into one array, sharing the same key:
First Array:
array(3) {
[0]=>
array(1) {
["Camera1"]=>
string(14) "192.168.101.71"
}
[1]=>
array(1) {
["Camera2"]=>
string(14) "192.168.101.72"
}
[2]=>
array(1) {
["Camera3"]=>
string(14) "192.168.101.74"
}
}
Second Array:
array(3) {
[0]=>
array(1) {
["Camera1"]=>
string(2) "VT"
}
[1]=>
array(1) {
["Camera2"]=>
string(2) "UB"
}
[2]=>
array(1) {
["Camera3"]=>
string(2) "FX"
}
}
As you can see, they share the same key (Camera1, Camera2, Camera3, etc..)
Here is what I have tried:
$Testvar = array_merge($NewArrayCam,$IpAddressArray);
foreach ($Testvar AS $Newvals){
$cam = array();
foreach($Newvals AS $K => $V){
$cam[] = array($K => $V);
}
Ideally I would look to format the two arrays in such a way that array_merge_recursive would simply merge the arrays without too much fuss.
However I did come up with a solution that used array_map.
$array1 = array(
array("Camera1" => "192.168.101.71"),
array("Camera2" => "192.168.101.72"),
array("Camera3" => "192.168.101.74"),
);
$array2 = array(
array("Camera1" => "VT"),
array("Camera2" => "UB"),
array("Camera3" => "FX")
);
$results = array();
array_map(function($a, $b) use (&$results) {
$key = current(array_keys($a));
$a[$key] = array('ip' => $a[$key]);
// Obtain the key again as the second array may have a different key.
$key = current(array_keys($b));
$b[$key] = array('name' => $b[$key]);
$results += array_merge_recursive($a, $b);
}, $array1, $array2);
var_dump($results);
The output is:
array (size=3)
'Camera1' =>
array (size=2)
'ip' => string '192.168.101.71' (length=14)
'name' => string 'VT' (length=2)
'Camera2' =>
array (size=2)
'ip' => string '192.168.101.72' (length=14)
'name' => string 'UB' (length=2)
'Camera3' =>
array (size=2)
'ip' => string '192.168.101.74' (length=14)
'name' => string 'FX' (length=2)
Try to use array_merge_recursive.
Use array_merge_recursive :
Convert all numeric key to strings, (make is associative array)
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
Ref : http://php.net/array_merge_recursive
For your nesting level will be enough this:
$sumArray = array_map(function ($a1, $b1) { return $a1 + $b1; }, $array1, $array2);
For deeper nesting it wont work.
If both arrays have the same numbers of levels and keys this should work:
$array3 = array();
foreach ($array1 as $key1 => $value1) {
// store IP
$array3['Camera'.$key1]['IP'] = $value['Camera'.$key1];
// store type of cam
$array3['Camera'.$key1]['Type'] = $array2[$key]['Camera'.$key1];
}
At the end $array3 should be something like:
$array3 = array {
["Camera1"] => {['IP'] => "192.168.101.71", ['Type'] => "VT" }
["Camera2"] => {['IP'] => "192.168.101.72", ['Type'] => "UB" }
["Camera3"] => {['IP'] => "192.168.101.74", ['Type'] => "FX" }
}
this would be one of the soluion:
function array_merge_custom($array1,$array2) {
$mergeArray = [];
$array1Keys = array_keys($array1);
$array2Keys = array_keys($array2);
$keys = array_merge($array1Keys,$array2Keys);
foreach($keys as $key) {
$mergeArray[$key] = array_merge_recursive(isset($array1[$key])?$array1[$key]:[],isset($array2[$key])?$array2[$key]:[]);
}
return $mergeArray;
}
$array1 = array(
array("Camera1" => "192.168.101.71"),
array("Camera2" => "192.168.101.72"),
array("Camera3" => "192.168.101.74"),
);
$array2 = array(
array("Camera1" => "VT"),
array("Camera2" => "UB"),
array("Camera3" => "FX")
);
echo '<pre>';
print_r(array_merge_custom($array1 , $array2));
The main problem are the arrays. Because of the way they are structured it becomes unnecessarily complicated to merge them. It they simply were normal associative arrays (i.e. array('Camera1' => 'VT') then it would be effortless to merge them.
I would suggest that you figure out how to format the data in such a way as to make it easier to work with.
This is a quick and dirty way of merging the two arrays. It takes one "camera" from one array, and then tries to find the corresponding "camera" in the other array. The function only uses the "cameras" in the $ips array, and only uses matching CameraN keys.
$ips = array(
array('Camera1' => '192.168.101.71'),
array('Camera2' => '192.168.101.72'),
array('Camera3' => '192.168.101.74'),
);
$names = array(
array('Camera1' => 'VT'),
array('Camera2' => 'UB'),
array('Camera3' => 'FX'),
);
function combineCameras($ips, $names) {
$output = array();
while ($ip = array_shift($ips)) {
$ident = key($ip);
foreach ($names as $key => $name) {
if (key($name) === $ident) {
$output[$ident] = array(
'name' => array_shift($name),
'ip' => array_shift($ip),
);
unset($names[$key]);
}
}
}
return $output;
}
var_dump(combineCameras($ips, $names));
Something like this should work:
$array1 = array(array("Camera1" => "192.168.101.71"), array("Camera2" => "192.168.101.72"), array("Camera3" => "192.168.101.74"));
$array2 = array(array("Camera1" => "VT"), array("Camera2" => "UB"), array("Camera3" => "FX"));
$results = array();
foreach($array1 as $key => $array){
foreach($array as $camera => $value){
$results[$camera]['ip'] = $value;
}
}
foreach($array2 as $key => $array){
foreach($array as $camera => $value){
$results[$camera]['name'] = $value;
}
}
print_r($results);
This worked for me.
I joined two arrays with the same keys
$array1 = ArrayUtils::merge($array1, $array2);
If you need preserve NumericKey, use
$array1 = ArrayUtils::merge($array1, $array2, true);
You could convert all numeric keys to strings and use array_replace_recursive which:
merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
Example
$arr1 = [
'rate' => 100
];
$arr2 = [
'rate' => 100,
'name' => 'Best Name In Town',
];
print_r(array_replace_recursive($arr1, $arr2));
Output
Array
(
[rate] => 100
[name] => Best Name In Town
)

Sort then split a PHP array?

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

Rebase array keys after unsetting elements [duplicate]

This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array:
$array = array(1,2,3,4,5);
If I were to dump the contents of the array they would look like this:
array(5) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
When I loop through and unset certain keys, the index gets all jacked up.
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
unset($array[$i]);
}
}
Subsequently, if I did another dump now it would look like:
array(3) {
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
Is there a proper way to reset the array so it's elements are Zero based again ??
array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(5)
}
Try this:
$array = array_values($array);
Using array_values()
Got another interesting method:
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
$array = array_merge($array);
Now the $array keys are reset.
Use array_splice rather than unset:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
Working sample here.
Just an additive.
I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."
First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.
Here's my simple, working example:
$array = array(1,2,3,4,5);
for ($i = 0; $i < count($array); $i++) {
if($array[$i] == 1 || $array[$i] == 2) {
array_splice($array, $i, 1);
$i--;
}
}
Will output:
array(3) {
[0]=> int(3)
[1]=> int(4)
[2]=> int(5)
}
This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:
$files = array(
array(
'name' => 'example.zip',
'size' => '100000000',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '10726556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '110726556',
'type' => 'application/x-zip-compressed',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example2.zip',
'size' => '12356556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
'deleteUrl' => 'server/php/?file=example2.zip',
'deleteType' => 'DELETE'
)
);
for ($i = 0; $i < count($files); $i++) {
if ($i > 0) {
if (is_array($files[$i-1])) {
if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
$i--;
array_splice($files, $i, 1);
}
}
}
}
Will output:
array(1) {
[0]=> array(6) {
["name"]=> string(11) "example.zip"
["size"]=> string(9) "110726556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
}
[1]=> array(6) {
["name"]=> string(11) "example2.zip"
["size"]=> string(9) "12356556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
}
}
As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.
I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.
100% working for me ! After unset elements in array you can use this for re-indexing the array
$result=array_combine(range(1, count($your_array)), array_values($your_array));
Late answer but, after PHP 5.3 could be so;
$array = array(1, 2, 3, 4, 5);
$array = array_values(array_filter($array, function($v) {
return !($v == 1 || $v == 2);
}));
print_r($array);
Or you can make your own function that passes the array by reference.
function array_unset($unsets, &$array) {
foreach ($array as $key => $value) {
foreach ($unsets as $unset) {
if ($value == $unset) {
unset($array[$key]);
break;
}
}
}
$array = array_values($array);
}
So then all you have to do is...
$unsets = array(1,2);
array_unset($unsets, $array);
... and now your $array is without the values you placed in $unsets and the keys are reset
In my situation, I needed to retain unique keys with the array values, so I just used a second array:
$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);
$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);

Categories