简体   繁体   中英

PHP Associative Array to JSON

I need to have data output in a very specific format to be used with something.

$product = Product::with('product_attribute_values', 'product_attribute_values.product_attribute_key')->find(2);

$product_decoded = json_decode($product, true);

I need to extract product attribute values into a specific format and it currently looks like:

在此处输入图片说明

I wish for it be like:

{
    "Material":"Plastic", 
    "Printing Method":"Pad", 
    "Ink Colour":"Black", 
    "Barrel Colour":"Silver", 
    "Grip Colour":"Black"
}

I have attempted this:

$final_array = array();

foreach($product_decoded['product_attribute_values'] as $pav) {
     $array = [
          $pav['product_attribute_key']['name'] => $pav['name']
     ];

     array_push($final_array, $array);
}

return json_encode($final_array);

This results in data looking like:

[
    {"Material":"Plastic"},
    {"Printing Method":"Pad"},
    {"Ink Colour":"Black"},
    {"Barrel Colour":"Silver"},
    {"Grip Colour":"Black"}
]

How would this be achieved?

You can do it like this:

foreach($product_decoded['product_attribute_values'] as $pav) {
     $array[$pav['product_attribute_key']['name']] = $pav['name'];
}

return json_encode($array);

For something like this you could use collections :

return collect($product_decoded['product_attribute_values'])
    ->pluck('name', 'product_attribute_key.name')
    ->toJson();

Alternatively, you could use the array helpers :

$finalArray = Arr::pluck($product_decoded['product_attribute_values'],'name', 'product_attribute_key.name' );

return json_encode($finalArray);

You need to have it in an object instead of an array.

$item = array("Material"=>"Plastic", "Printing Method"=>"Pad", "Ink Colour"=>"Black", "Barrel Colour"=>"Silver", "Grip Colour"=>"Black");

echo json_encode($item);

will result in this JSON:

[
    {"Material":"Plastic"},
    {"Printing Method":"Pad"},
    {"Ink Colour":"Black"},
    {"Barrel Colour":"Silver"},
    {"Grip Colour":"Black"}
]

Which is correct JSON array syntax.

In order to get

{
    "Material":"Plastic", 
    "Printing Method":"Pad", 
    "Ink Colour":"Black", 
    "Barrel Colour":"Silver", 
    "Grip Colour":"Black"
}

You would need soemthing like

$item->Material = "Plastic";
$item->PrintingMethod = "Pad";
$item->InkColour = "Black";
$item->Barrel Colour = "Silver";
$item->GripColour = "Black;

json_encode($item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM