0

what i want to do is that i am creating php array dynamic .i dont know about the elements in the array. lets say i have array like this

$mix_array =array('1','3','6','1','5','3','6','5','1','7','3','9');

i want slicing of this array.i want to create arrays from the above array but of common elements like

$array_1 = ('1','1','1');
$array_2 = ('3','3','3');
$array_3 = ('6','6');
$array_4 = ('5','5');
$array_5 = ('9');
$array_6 = ('7');

that is first find common elements in original array and make other array from that

1
  • array_slice(), trying intersect but not well enough Commented Mar 25, 2012 at 20:44

4 Answers 4

2

Better make assosative array instead of typing $array_1, $array_2. And instead of making array with same values like array('1', '1', '1'), you can just keep the amount of value like array('1' => 3)

$mix_array = array ('1','3','6','1','5','3','6','5','1','7','3','9');
$group_array = array();
foreach ($mix_array as $value) {
    if(isset($group_array[$value])) {
        $group_array[$value]++;
    }
    else {
        $group_array[$value] = 1;
    }
}

print_r($group_array);

Result

Array
(
[1] => 3
[3] => 3
[6] => 2
[5] => 2
[7] => 1
[9] => 1
)

Or as Josh said simply use array_count_values()

Sign up to request clarification or add additional context in comments.

1 Comment

A native function already exists for this, array_count_values($arr).
1

There are several ways to do it, here is an example (by the way, quite inefficient, but enough if it is a short work):

<?php
$mix_array = array('1','3','6','1','5','3','6','5','1','7','3','9');
$sliced_array = array();

foreach($mix_array as $k => $v) {
    if( count($sliced_array[$v]) > 0 ) {
        array_push($sliced_array[$v], $v);
    } else {
        $sliced_array[$v] = array($v);
    }
}
?>

You should take a look at http://es.php.net/manual/en/ref.array.php

Comments

1

You can use array_count_values for this:

$array = array_count_values($mix_array);
/* $array will have the following content:
   $array{
       1 => 3
       3 => 3
       6 => 2
     ...
*/

If you really need the sliced version, then you can use array_fill

$result = array();
$i = 0;
for($array as $key=>$value)
    $result[$i++] = array_fill(0,$value,$key);
/* $result[0] = (1,1,1),
   $result[1] = (3,3,3),
     ...
*/

Comments

1

array_slice() // http://php.net/manual/en/function.array-slice.php

or

array_chunk() // http://www.php.net/manual/en/function.array-chunk.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.