0

I have array 1 and it should be 2

Does anyone have an idea / solution?

Do i need foreach or for loop?

1.

Array
(
[0] => Array
    (
        [category_id] => 5
        [category] => Pages
    )

)

Must be:

Array
(
[0] => Array
    (
        [5] => Pages
    )

)

I have this but this doent work...

    for($x = 0; $x <= $counter; $x++){
        foreach ($Categories[$x] as $key => $value){
            echo $key.' '. $value.'<br>';
        }
        $test[$x]['category_id'] .= $Categories[$x]['category'];
    }

Thanks for all the help!

5
  • Yes you need foreach. Commented May 14, 2013 at 6:38
  • Do you want to (unset) the id? Commented May 14, 2013 at 6:39
  • $arr[$i] = array($arr['category_id'] => $arr['category']); something like this in loop should work I am not sure what exactly you want to get. Commented May 14, 2013 at 6:40
  • @Robert Podwika Well i am getting 1 from the database and i want to manipulate it "must be" Commented May 14, 2013 at 6:43
  • @Bas: You code executing in infinite loop. Commented May 14, 2013 at 6:44

3 Answers 3

2

Code:

<?php

$arr = array(
    array(
        'category_id' => 5      ,
        'category'    => 'Pages',
    ),
);

$new = array();
foreach ($arr as $item) {
    $new[] = array(
        $item['category_id'] => $item['category']
    );
}

print_r($new);

Result:

Array
(
    [0] => Array
        (
            [5] => Pages
        )

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

Comments

2
$output=array();
foreach($array as $k=>$v)
{
  $output[$v['category_id']]=$v['category'];
}

echo "<pre />";
print_r($output);

Demo1

Demo 2

for multidimensinal result :

$output=array();
foreach($array as $k=>$v)
{
  $output[][$v['category_id']]=$v['category'];
}

echo "<pre />";
print_r($output);

3 Comments

I think @Bas requires multi-dementional result.
@CertaiN check answer for multidimensional result
@CertaiN : do not downvote any answer, if it doesn't belong to you or your question
1

As you said you will need a foreach loop to manupulate you array.

Example

$array = array
(
'0' => array
    (
        'category_id' => '5',
        'category' => 'Pages'
    )
);  


$new_array = array();
foreach($array as $val)
{
     $new_array[$val['category_id']] = $val['category'];
}

var_dump($new_array);

this will output

array(1) { [5]=> string(5) "Pages" } 

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.