0

i had a array to each its item was object , i've converted that array with following code :

json_decode(json_encode($array), true)

that the result of code was a array like this :

[
  '1'=>[
   'slug'=>'a'
   'title'=>'foo' 
  ],
  '2'=>[
   'slug'=>'b'
   'title'=>'bar' 
  ],
  '3'=>[
   'slug'=>'c'
   'title'=>'foo' 
  ],
]

now i want to covert this array to somethings like this

 [
   'a'=>'foom',
   'b'=>'bar',
   'c'=>'foo',
 ] 

how can i do it ??

3 Answers 3

2

Use foreach and array_combine()

foreach ($your_array as $key => $value) {
  // get all the keys in $slug array
  $slug[] = $value['slug'];
  // get all the values in $title array
  $title[] = $value['title'];
}
// finally combine and get your required array
$required_array = array_combine($slug, $title);

I think it can also be acheived with -

$requiredArray = array_combine(
   array_column($your_array, 'slug'), 
   array_column($your_array, 'title')
);
Sign up to request clarification or add additional context in comments.

1 Comment

thnks @jitendrapurohit the second way work like a charm , the first way is currect too and i've test it before but there are alot of item in the array so it seems a little cheap .
1

You have to iterate over the initial array and create the new one like this:

$array = [
  '1'=>[
   'slug'=>'a'
   'title'=>'foo' 
  ],
  '2'=>[
   'slug'=>'b'
   'title'=>'bar' 
  ],
  '3'=>[
   'slug'=>'c'
   'title'=>'foo' 
  ],
];

$result = [];
foreach($array as $elem){
   $index = $elem["slug"];
   $value= $elem["title"];
   $result[$index] = $value; 
}

Comments

1
foreach($array as $elem){
    $result[$elem["slug"]] = $elem["title"]; 
}

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.