ian
ian

Reputation: 313

Simplify php array from 5 variable to 2 variables

I have an array $bobby with the following arrays inside. It is sorted by id.

1
    id="1"  
    color="blue"
    size="7"
    height="10"
    beebop="z"

2
    id="2"  
    color="red"
    size="64"
    height="52"
    beebop="y"
3
    id="3"  
    color="pink"
    size="72"
    height="39"
    beebop="not_x"

I am having trouble creating the php function that will create a simplified array ($bobby_simplified) which only contains two values, id and color? So, the new array would look like this:

1
    id="1"  
    color="blue"
2
    id="2"  
    color="red"
3
    id="3"  
    color="pink"

Also, in that function, can we sort by color ascending?


I tried the following but with no luck:

            foreach ($bobby AS $bobby_simplified) {
                $id = $bobby_simplified['id'];
                $color = $bobby_simplified['color'];
            }

Upvotes: 0

Views: 62

Answers (4)

apelidoko
apelidoko

Reputation: 790

try this, already tested, added sorting by color

$array = [1=>['id'=> '1', 'color'=> 'blue', 'size'=>'7', 'height'=>'10', 'beebop'=>'z'],
          2=>['id'=> '2', 'color'=> 'red', 'size'=>'64', 'height'=>'52', 'beebop'=>'y'],
          3=>['id'=> '3', 'color'=> 'pink', 'size'=>'72', 'height'=>'39', 'beebop'=>'not_x'],
         ];

foreach($array as $arr){

        $arr = array_splice($arr,0,2);
        print_r($arr); 

        $array2[] = $arr;
}
    echo "<br>";
    print_r($array2);

    echo "<br>";



function sortBy($field, &$array, $direction = 'asc')
{
    usort($array, create_function('$a, $b', '
        $a = $a["' . $field . '"];
        $b = $b["' . $field . '"];

        if ($a == $b)
        {
            return 0;
        }

        return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
    '));

    return true;
}

sortBy('color',   $array2, 'asc');
print_r($array2);

Upvotes: -1

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can use the array_map() function to get an new array, and array_slice() to get first two elements of the subarray. Check the live demo.

$simplified = array_map(function($v){return array_slice($v, 0, 2, true);}, $array);

Upvotes: 1

enda
enda

Reputation: 30

try something like this

foreach ($bobby AS $bobby_simplified){
$res = array("id"=>$bobby_simplified['id'],"color"=>$bobby_simplified['color']);
}
print_r($res);

Upvotes: 1

Enstage
Enstage

Reputation: 2126

You can sort the array alphabetically by color using:

usort($arr, function($a, $b) { return strcmp($a['color'], $b['color']); });

Upvotes: 1

Related Questions