php handle arrays - php

I have an array that contains entries that themselves contain two types of entries.
For simplicity sake, let's say that the entries are like this:
a|1
b|4
a|2
c|5
b|3
etc.
In fact they represent categories and subcategories in my database.
I will use explode to break these entries into letters and digits.
The question is: I want to group them by category.
What's the easiest way to create a multilevel array, which could be sorted by letters:
a|1
a|2
b|4
b|3
c|5
?

How about something like this?
$input = array('a|1','b|4','a|2','c|5','b|3');
$output = array();
foreach($input as $i){
list($key,$val) = explode("|",$i);
$output[$key][] = $val;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 2
)
[b] => Array
(
[0] => 4
[1] => 3
)
[c] => Array
(
[0] => 5
)
)

<?php
$your_array = array();
$your_array[a] = array('1','2','3');
$your_array[b] = array('4','5','6');
print_r($your_array);
?>

I take it that your entries are strings (relying on the fact that you want to use explode() on them).
If so you can simply sort the array by using sort($array), and then iterate on that array and explode the values and put them in another array, which will be sorted by the previous array's order.

Related

How to cut array into two

I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.

How to create an array from string seperated values?

I have an array like:
Array
(
[0] => Mechanical Engineering,CEO
)
Now I want to convert it in this form:
Array
(
[0] => Mechanical Engineering
[1] => CEO
)
You can use like below.
$str = 'Mechanical Engineering,CEO';
$arrayStr = explode(',',$str );
print_r($arrayStr);
Note: Assuming your input array has only one key "Mechanical Engineering,CEO".
We need current() function to access the array element.
Since you want to split your data every time there's a comma, we need explode()
function.
$input = array("Mechanical Engineering,CEO");
$output = explode(",", current($input));

Two PHP arrays, unset positions that are only present in one array

I have two arrays (in PHP):
ArrayA
(
[0] => 9
[1] => 1
[2] => 2
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
I want to make two new arrays, where I have only the elements declared in both of the arrays, like the following:
ArrayA
(
[0] => 9
[1] => 1
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
In this example ArrayA[2] doesn't exist, so ArrayB[2] has been unset.
I wrote this for loop:
for ($i = 0, $i = 99999, $i++){
if (isset($ArrayA[$i]) AND isset($ArrayB[$i]) == FALSE)
{
unset($ArrayA[$i],$ArrayB[$i]);
}
}
But it's not great because it tries every index between 0 and a very big number (99999 in this case). How can I improve my code?
The function you're looking for is array_intersect_key:
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
Since you want both arrays, you'll have to run it twice, with the parameters in opposite orders, as it only keeps keys from the first array. An example:
$arrayA_filtered = array_intersect_key($arrayA, $arrayB);
$arrayB_filtered = array_intersect_key($arrayB, $arrayA);
Also, although a for loop wasn't ideal in this case, in other cases where you find yourself needing to loop through sparse array (one where not every number is set), you can use a foreach loop:
foreach($array as $key => $value) {
//Do stuff
}
One very important thing to note about PHP arrays is that they are associative. You can't simply use a for loop, as the indices are not necessarily a range of integers. Consider what would happen if you applied this algorithm twice! You'd get out of bounds errors as $arrayA[2] and $arrayB[2] no longer exist!
I would iterate through the arrays using nested foreach statements. I.e.
$outputA = array();
$outputB = array();
foreach ($arrayA as $keyA => $itemA) {
foreach ($arrayB as $keyB => $itemB) {
if ($keyA == $keyB) {
$outputA[$keyA] = $itemA;
$outputB[$keyB] = $itemB;
}
}
This should give you two arrays, $outputA and $outputB, which look just like $arrayA and $arrayB, except they only include key=>value pairs if the key was present in both original arrays.
foreach($arrayA as $k=>$a)
if (!isset($arrayB[$k]))
unset($arrayA[$k];
Take a look to php : array_diff
http://docs.php.net/manual/fr/function.array-diff.php

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories