1

How to convert multidimensional array from the example below

Array

(

    [0] => Array

        (

            [cf] => Juan

            [nf] => 5

        )

    [1] => Array

        (

            [cf] => Kyu

            [nf] => 10

        )

)

to an simple array using values as keys and values where [cf] is a key and [nf] is value

Array
(
"Juan"=>"5",
"Kyu"=>"10"
)

6 Answers 6

1
$arr = array(
  0 => array(
      'cf' => 'Juan',
      'nf' => 5
    ),
  1 => array(
      'cf' => 'Kyu',
      'nf' => 10
    )
);

$result = array();

foreach($arr as $key => $value) {
  $result[$value['cf']] = $value['nf'];
}

print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

0

try like this:

$a = array(array('cf'=>'joan', 'nf'=>'5'), array('cf'=>'lol', 'nf'=>'55'));
$new = array();

foreach( $a as $k ) {
    $new[$k[cf]] = $k[nf];
}
print_r( $new )

http://codepad.org/xVbcDXLD

Comments

0
$x=array(
    0=>array(
        "cf"=>"Juan",
        "nf" => 5,
    ),
    1=>array(
        "cf"=>"Kyu",
        "nf" => 10,
    ),
);

foreach($x as $k=>$v) $result[$v["cf"]]=$v["nf"];

print_r($result);

Comments

0

you iterate through it, and build up your array, like this:

$mysimplearray = array();
foreach($originalarray as $id => $innerarray) {
   $mysimplearray[$innerarray["cf"]] = $innerarray["nf"];
} 

voila, your data is stored now as a simple 1 dimension array, in $simplearray.

Comments

0

Here you have your function:

$array =
array (
    0 => Array
        (
            'cf' => 'Juan',
            'nf' => 5
        ),
    1 => Array
        (
            'cf' => 'Kyu',
            'nf' => 10
        )
);

$new_array = array();
foreach($array as $value => $new_array_elem) {
    $key = $new_array_elem['cf'];
    $value = $new_array_elem['nf'];
    $new_array["$key"] = $value;
}

print_r($new_array);

Comments

0

You can do like ..

<?php
$arr = array( 0 => array( "cf" => "Juan", "nf" => 5, ),1 => array(  "cf" => "Kyu", "nf" => 10, ),);

foreach ($arr as $arr1)
{
    foreach($arr1 as $k=>$v)
    {
        $arrnew[]=$v; // Adding just the values to the temp array
    }
    $new_arr[$arrnew[0]]=$arrnew[1]; //Your new array gets those values from the temp array
    unset($arrnew); //Deleting your temp array
}

print_r($new_arr); //Printing the results

OUTPUT :

Array
(
    [Juan] => 5
    [Kyu] => 10
)

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.