I'm having a string like this..
food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'
I tried explode option
But I'm getting an array like this
Array
(
[0] => 'food_item' => 'Butter Croissant'
[1] => 'food_id' => '1'
[2] => 'quantity' => '1'
[3] => 'price' => '140'
)
But I should need to make it as an array like as follows,
Array
(
[food_item] => 'Butter Croissant'
[food_id] => '1'
[quantity] => '1'
[price] => '140'
)
how should I do this,Someone please help me..
Thank you in advance..
Try:
$str = "food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'";
$mainArray = explode(",",$str);
$newArray = array();
foreach($mainArray as $main) {
$innerArray = explode("=>",$main);
$newArray[trim($innerArray[0])] = trim($innerArray[1]);
}
Output:
Array
(
[food_item] => 'Butter Croissant'
[food_id] => '1'
[quantity] => '1'
[price] => '140'
)
You can do it like below:-
<?php
$string = "food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'"; // original string
$first_array = explode(',',$string); // your first explode with `,`
$final_array = array(); // create a new empty array
foreach($first_array as $arr){ // iterate over previously exploded array
$data = explode('=>',$arr); // now explode the value again with `=>`
$final_array[trim($data[0])] = trim($data[1]); // add it to final array in the form of key=>value pair
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/609356
Note:- this is easiest stuff to do and to understand also.thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With