Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How transform this array?

Tags:

arrays

php

Here is data

$array = array(
    'random' => 1,
    'pewpew' => 2,
    'temp' => 5,
    'xoxo' => 3,
    'qweqweqe' => 4,
);

$fields = array('random', 'xoxo', 'temp');

I need to get in result:

$result = array(
    'random' => 1,
    'xoxo' => 3,
    'temp' => 5,
);

I mean keys presence/order from $fields apply to $array.

The question is: Can I perform this transformation using only array_ functions? (I don't wanna use iteations) If yes: can you link me function that I need?

(sorry for spelling mistakes)

upd.

PHP 5.2

like image 300
Miraage Avatar asked Jun 29 '12 15:06

Miraage


People also ask

How do you change an array in JavaScript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.

Does shift change the array?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


2 Answers

$result=array_intersect_key($array ,array_flip($fields) );
like image 105
Waygood Avatar answered Oct 19 '22 07:10

Waygood


// little trick required here...
$fields = array('random' => 0, 'xoxo' => 0, 'temp' => 0);
$result = array_intersect_key($array,$fields);
like image 27
LeleDumbo Avatar answered Oct 19 '22 08:10

LeleDumbo