how to create json array of objects from php array in php? -
i having php array containing integer numbers below
array ( [0] => 41 [1] => 64 [2] => 51 [3] => 42 [4] => 65 [5] => 52 [6] => 66 [7] => 67 )
now want create json array of object this.
[{"assosiated_id": 41}, {"assosiated_id": 42}, {"assosiated_id": 51}, {"assosiated_id": 52}, {"assosiated_id": 64}, {"assosiated_id": 65}, {"assosiated_id": 66}, {"assosiated_id": 67}]
i have tried converting array assosiative array encode json assosiative array can not have duplicate values.please tell best way it?
$a = [41, 64, 51, 42, 65, 52, 66, 67]; sort($a); $b = []; foreach ($a $v) { $b[] = ['associated_id' => $v]; } echo json_encode($b);
gives
[{"associated_id":41},{"associated_id":64},{"associated_id":51}, {"associated_id":42},{"associated_id":65},{"associated_id":52},{"associated_id":66},{"associated_id":67}]
alternatively can use mark baker's oneliner in comments
if using older version of php may have code this
$a = array(41, 64, 51, 42, 65, 52, 66, 67); sort($a); $b = array(); foreach ($a $v) { $b[] = array('associated_id' => $v); } echo json_encode($b);
Comments
Post a Comment