4

This is my db result,

Array ([0] => Array ( [shopname] => Shop name [fueltype] => Pertol [amount] => 1000 ) 
       [1] => Array ( [shopname] => dfsdfsd [fueltype] => Pertol [amount] => 54456 )
       [2] => Array ( [shopname] => dfsdfsd [fueltype] => Disel [amount] => 54456 )
)

I need result like

[["Shop name", "Pertol", 1000],["dfsdfsd", "Pertol", 54456],["Shop name", "Disel", 54456]]

How to get like this, I have no idea?

2
  • 1
    First do a conversion from key value to value only (array_values()) and then a json_encode()... Those are your friends now... ;) Commented Jul 9, 2015 at 7:56
  • Ajin it's your responsibility to check answers and mark one answer which is most suitable to you. It will help future visitors to find out solution easily.Thanks.(You can up-vote others too if they are useful) Commented Sep 1, 2017 at 6:44

3 Answers 3

3

array_map() along with array_values() will work for you:-

<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ), 
        '1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
        '2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);


$values_data_only = array_map('array_values', $array);
$desire_result = json_encode($values_data_only);
echo $desire_result;

?>

Output:- https://eval.in/395344

Also via simple foreach() it is possible:-

<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ), 
        '1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
        '2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);

$new_array = array();

foreach ($array as $k=> $arr){
    $new_array[$k][] = $arr['shopname'];
    $new_array[$k][] = $arr['fueltype'];
    $new_array[$k][] = $arr['amount'];
}
echo "<pre/>";print_r($new_array);
$desired_result_2 = json_encode($new_array);
echo $desired_result_2;
?>

Output:-https://eval.in/395354

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

Comments

2
$mapped = array_map('array_values', $input_array); // apply filter so we dont get the keys
$json = json_encode($mapped);

Comments

0

Just try with:

$input  = array( /* your input data */ );
$output = array();

foreach ($input as $data) {
  $output[] = array_values($data);
}

2 Comments

I think you dont need to initialize $output, outside foreach, it will save you a line of code !
@Viral That's a bad idea.

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.